File:  [gforth] / gforth / doc / gforth.ds
Revision 1.231: download - view: text, annotated - select for diffs
Sat Jan 1 14:22:48 2011 UTC (13 years, 3 months ago) by pazsan
Branches: MAIN
CVS tags: HEAD
Added strings into documentation

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: 
    4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    5: @comment 1. x-ref all ambiguous or implementation-defined features?
    6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
    7: @comment 3. words in miscellaneous section need a home.
    8: @comment 4. search for TODO for other minor and major works required.
    9: @comment 5. [rats] change all @var to @i in Forth source so that info
   10: @comment    file looks decent.
   11: @c          Not an improvement IMO - anton
   12: @c          and anyway, this should be taken up
   13: @c          with Karl Berry (the texinfo guy) - anton
   14: @c
   15: @c Karl Berry writes:
   16: @c  If they don't like the all-caps for @var Info output, all I can say is
   17: @c  that it's always been that way, and the usage of all-caps for
   18: @c  metavariables has a long tradition.  I think it's best to just let it be
   19: @c  what it is, for the sake of consistency among manuals.
   20: @c
   21: @comment .. would be useful to have a word that identified all deferred words
   22: @comment should semantics stuff in intro be moved to another section
   23: 
   24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
   25: 
   26: @comment %**start of header (This is for running Texinfo on a region.)
   27: @setfilename gforth.info
   28: @include version.texi
   29: @settitle Gforth Manual
   30: @c @syncodeindex pg cp
   31: 
   32: @macro progstyle {}
   33: Programming style note:
   34: @end macro
   35: 
   36: @macro assignment {}
   37: @table @i
   38: @item Assignment:
   39: @end macro
   40: @macro endassignment {}
   41: @end table
   42: @end macro
   43: 
   44: @comment macros for beautifying glossary entries
   45: @macro GLOSS-START {}
   46: @iftex
   47: @ninerm
   48: @end iftex
   49: @end macro
   50: 
   51: @macro GLOSS-END {}
   52: @iftex
   53: @rm
   54: @end iftex
   55: @end macro
   56: 
   57: @comment %**end of header (This is for running Texinfo on a region.)
   58: @copying
   59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
   60: a fast and portable implementation of the ANS Forth language.  It
   61: serves as reference manual, but it also contains an introduction to
   62: Forth and a Forth tutorial.
   63: 
   64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008,2009,2010 Free Software Foundation, Inc.
   65: 
   66: @quotation
   67: Permission is granted to copy, distribute and/or modify this document
   68: under the terms of the GNU Free Documentation License, Version 1.1 or
   69: any later version published by the Free Software Foundation; with no
   70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
   71: and with the Back-Cover Texts as in (a) below.  A copy of the
   72: license is included in the section entitled ``GNU Free Documentation
   73: License.''
   74: 
   75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
   76: this GNU Manual, like GNU software.  Copies published by the Free
   77: Software Foundation raise funds for GNU development.''
   78: @end quotation
   79: @end copying
   80: 
   81: @dircategory Software development
   82: @direntry
   83: * Gforth: (gforth).             A fast interpreter for the Forth language.
   84: @end direntry
   85: @c The Texinfo manual also recommends doing this, but for Gforth it may
   86: @c  not make much sense
   87: @c @dircategory Individual utilities
   88: @c @direntry
   89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   90: @c @end direntry
   91: 
   92: @titlepage
   93: @title Gforth
   94: @subtitle for version @value{VERSION}, @value{UPDATED}
   95: @author Neal Crook
   96: @author Anton Ertl
   97: @author David Kuehling
   98: @author Bernd Paysan
   99: @author Jens Wilke
  100: @page
  101: @vskip 0pt plus 1filll
  102: @insertcopying
  103: @end titlepage
  104: 
  105: @contents
  106: 
  107: @ifnottex
  108: @node Top, Goals, (dir), (dir)
  109: @top Gforth
  110: 
  111: @insertcopying
  112: @end ifnottex
  113: 
  114: @menu
  115: * Goals::                       About the Gforth Project
  116: * Gforth Environment::          Starting (and exiting) Gforth
  117: * Tutorial::                    Hands-on Forth Tutorial
  118: * Introduction::                An introduction to ANS Forth
  119: * Words::                       Forth words available in Gforth
  120: * Error messages::              How to interpret them
  121: * Tools::                       Programming tools
  122: * ANS conformance::             Implementation-defined options etc.
  123: * Standard vs Extensions::      Should I use extensions?
  124: * Model::                       The abstract machine of Gforth
  125: * Integrating Gforth::          Forth as scripting language for applications
  126: * Emacs and Gforth::            The Gforth Mode
  127: * Image Files::                 @code{.fi} files contain compiled code
  128: * Engine::                      The inner interpreter and the primitives
  129: * Cross Compiler::              The Cross Compiler
  130: * Bugs::                        How to report them
  131: * Origin::                      Authors and ancestors of Gforth
  132: * Forth-related information::   Books and places to look on the WWW
  133: * Licenses::                    
  134: * Word Index::                  An item for each Forth word
  135: * Concept Index::               A menu covering many topics
  136: 
  137: @detailmenu
  138:  --- The Detailed Node Listing ---
  139: 
  140: Gforth Environment
  141: 
  142: * Invoking Gforth::             Getting in
  143: * Leaving Gforth::              Getting out
  144: * Command-line editing::        
  145: * Environment variables::       that affect how Gforth starts up
  146: * Gforth Files::                What gets installed and where
  147: * Gforth in pipes::             
  148: * Startup speed::               When 14ms is not fast enough ...
  149: 
  150: Forth Tutorial
  151: 
  152: * Starting Gforth Tutorial::    
  153: * Syntax Tutorial::             
  154: * Crash Course Tutorial::       
  155: * Stack Tutorial::              
  156: * Arithmetics Tutorial::        
  157: * Stack Manipulation Tutorial::  
  158: * Using files for Forth code Tutorial::  
  159: * Comments Tutorial::           
  160: * Colon Definitions Tutorial::  
  161: * Decompilation Tutorial::      
  162: * Stack-Effect Comments Tutorial::  
  163: * Types Tutorial::              
  164: * Factoring Tutorial::          
  165: * Designing the stack effect Tutorial::  
  166: * Local Variables Tutorial::    
  167: * Conditional execution Tutorial::  
  168: * Flags and Comparisons Tutorial::  
  169: * General Loops Tutorial::      
  170: * Counted loops Tutorial::      
  171: * Recursion Tutorial::          
  172: * Leaving definitions or loops Tutorial::  
  173: * Return Stack Tutorial::       
  174: * Memory Tutorial::             
  175: * Characters and Strings Tutorial::  
  176: * Alignment Tutorial::          
  177: * Floating Point Tutorial::     
  178: * Files Tutorial::              
  179: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  180: * Execution Tokens Tutorial::   
  181: * Exceptions Tutorial::         
  182: * Defining Words Tutorial::     
  183: * Arrays and Records Tutorial::  
  184: * POSTPONE Tutorial::           
  185: * Literal Tutorial::            
  186: * Advanced macros Tutorial::    
  187: * Compilation Tokens Tutorial::  
  188: * Wordlists and Search Order Tutorial::  
  189: 
  190: An Introduction to ANS Forth
  191: 
  192: * Introducing the Text Interpreter::  
  193: * Stacks and Postfix notation::  
  194: * Your first definition::       
  195: * How does that work?::         
  196: * Forth is written in Forth::   
  197: * Review - elements of a Forth system::  
  198: * Where to go next::            
  199: * Exercises::                   
  200: 
  201: Forth Words
  202: 
  203: * Notation::                    
  204: * Case insensitivity::          
  205: * Comments::                    
  206: * Boolean Flags::               
  207: * Arithmetic::                  
  208: * Stack Manipulation::          
  209: * Memory::                      
  210: * Control Structures::          
  211: * Defining Words::              
  212: * Interpretation and Compilation Semantics::  
  213: * Tokens for Words::            
  214: * Compiling words::             
  215: * The Text Interpreter::        
  216: * The Input Stream::            
  217: * Word Lists::                  
  218: * Environmental Queries::       
  219: * Files::                       
  220: * Blocks::                      
  221: * Other I/O::                   
  222: * OS command line arguments::   
  223: * Locals::                      
  224: * Structures::                  
  225: * Object-oriented Forth::       
  226: * Programming Tools::           
  227: * C Interface::                 
  228: * Assembler and Code Words::    
  229: * Threading Words::             
  230: * Passing Commands to the OS::  
  231: * Keeping track of Time::       
  232: * Miscellaneous Words::         
  233: 
  234: Arithmetic
  235: 
  236: * Single precision::            
  237: * Double precision::            Double-cell integer arithmetic
  238: * Bitwise operations::          
  239: * Numeric comparison::          
  240: * Mixed precision::             Operations with single and double-cell integers
  241: * Floating Point::              
  242: 
  243: Stack Manipulation
  244: 
  245: * Data stack::                  
  246: * Floating point stack::        
  247: * Return stack::                
  248: * Locals stack::                
  249: * Stack pointer manipulation::  
  250: 
  251: Memory
  252: 
  253: * Memory model::                
  254: * Dictionary allocation::       
  255: * Heap Allocation::             
  256: * Memory Access::               
  257: * Address arithmetic::          
  258: * Memory Blocks::               
  259: 
  260: Control Structures
  261: 
  262: * Selection::                   IF ... ELSE ... ENDIF
  263: * Simple Loops::                BEGIN ...
  264: * Counted Loops::               DO
  265: * Arbitrary control structures::  
  266: * Calls and returns::           
  267: * Exception Handling::          
  268: 
  269: Defining Words
  270: 
  271: * CREATE::                      
  272: * Variables::                   Variables and user variables
  273: * Constants::                   
  274: * Values::                      Initialised variables
  275: * Colon Definitions::           
  276: * Anonymous Definitions::       Definitions without names
  277: * Supplying names::             Passing definition names as strings
  278: * User-defined Defining Words::  
  279: * Deferred Words::              Allow forward references
  280: * Aliases::                     
  281: 
  282: User-defined Defining Words
  283: 
  284: * CREATE..DOES> applications::  
  285: * CREATE..DOES> details::       
  286: * Advanced does> usage example::  
  287: * Const-does>::                 
  288: 
  289: Interpretation and Compilation Semantics
  290: 
  291: * Combined words::              
  292: 
  293: Tokens for Words
  294: 
  295: * Execution token::             represents execution/interpretation semantics
  296: * Compilation token::           represents compilation semantics
  297: * Name token::                  represents named words
  298: 
  299: Compiling words
  300: 
  301: * Literals::                    Compiling data values
  302: * Macros::                      Compiling words
  303: 
  304: The Text Interpreter
  305: 
  306: * Input Sources::               
  307: * Number Conversion::           
  308: * Interpret/Compile states::    
  309: * Interpreter Directives::      
  310: 
  311: Word Lists
  312: 
  313: * Vocabularies::                
  314: * Why use word lists?::         
  315: * Word list example::           
  316: 
  317: Files
  318: 
  319: * Forth source files::          
  320: * General files::               
  321: * Redirection::                 
  322: * Search Paths::                
  323: 
  324: Search Paths
  325: 
  326: * Source Search Paths::         
  327: * General Search Paths::        
  328: 
  329: Other I/O
  330: 
  331: * Simple numeric output::       Predefined formats
  332: * Formatted numeric output::    Formatted (pictured) output
  333: * String Formats::              How Forth stores strings in memory
  334: * Displaying characters and strings::  Other stuff
  335: * Terminal output::             Cursor positioning etc.
  336: * Single-key input::            
  337: * Line input and conversion::   
  338: * Pipes::                       How to create your own pipes
  339: * Xchars and Unicode::          Non-ASCII characters
  340: 
  341: Locals
  342: 
  343: * Gforth locals::               
  344: * ANS Forth locals::            
  345: 
  346: Gforth locals
  347: 
  348: * Where are locals visible by name?::  
  349: * How long do locals live?::    
  350: * Locals programming style::    
  351: * Locals implementation::       
  352: 
  353: Structures
  354: 
  355: * Why explicit structure support?::  
  356: * Structure Usage::             
  357: * Structure Naming Convention::  
  358: * Structure Implementation::    
  359: * Structure Glossary::          
  360: * Forth200x Structures::        
  361: 
  362: Object-oriented Forth
  363: 
  364: * Why object-oriented programming?::  
  365: * Object-Oriented Terminology::  
  366: * Objects::                     
  367: * OOF::                         
  368: * Mini-OOF::                    
  369: * Comparison with other object models::  
  370: 
  371: The @file{objects.fs} model
  372: 
  373: * Properties of the Objects model::  
  374: * Basic Objects Usage::         
  375: * The Objects base class::      
  376: * Creating objects::            
  377: * Object-Oriented Programming Style::  
  378: * Class Binding::               
  379: * Method conveniences::         
  380: * Classes and Scoping::         
  381: * Dividing classes::            
  382: * Object Interfaces::           
  383: * Objects Implementation::      
  384: * Objects Glossary::            
  385: 
  386: The @file{oof.fs} model
  387: 
  388: * Properties of the OOF model::  
  389: * Basic OOF Usage::             
  390: * The OOF base class::          
  391: * Class Declaration::           
  392: * Class Implementation::        
  393: 
  394: The @file{mini-oof.fs} model
  395: 
  396: * Basic Mini-OOF Usage::        
  397: * Mini-OOF Example::            
  398: * Mini-OOF Implementation::     
  399: 
  400: Programming Tools
  401: 
  402: * Examining::                   Data and Code.
  403: * Forgetting words::            Usually before reloading.
  404: * Debugging::                   Simple and quick.
  405: * Assertions::                  Making your programs self-checking.
  406: * Singlestep Debugger::         Executing your program word by word.
  407: 
  408: C Interface
  409: 
  410: * Calling C Functions::         
  411: * Declaring C Functions::       
  412: * Calling C function pointers::  
  413: * Defining library interfaces::  
  414: * Declaring OS-level libraries::  
  415: * Callbacks::                   
  416: * C interface internals::       
  417: * Low-Level C Interface Words::  
  418: 
  419: Assembler and Code Words
  420: 
  421: * Assembler Definitions::       Definitions in assembly language
  422: * Common Assembler::            Assembler Syntax
  423: * Common Disassembler::         
  424: * 386 Assembler::               Deviations and special cases
  425: * AMD64 Assembler::             
  426: * Alpha Assembler::             Deviations and special cases
  427: * MIPS assembler::              Deviations and special cases
  428: * PowerPC assembler::           Deviations and special cases
  429: * ARM Assembler::               Deviations and special cases
  430: * Other assemblers::            How to write them
  431: 
  432: Tools
  433: 
  434: * ANS Report::                  Report the words used, sorted by wordset.
  435: * Stack depth changes::         Where does this stack item come from?
  436: 
  437: ANS conformance
  438: 
  439: * The Core Words::              
  440: * The optional Block word set::  
  441: * The optional Double Number word set::  
  442: * The optional Exception word set::  
  443: * The optional Facility word set::  
  444: * The optional File-Access word set::  
  445: * The optional Floating-Point word set::  
  446: * The optional Locals word set::  
  447: * The optional Memory-Allocation word set::  
  448: * The optional Programming-Tools word set::  
  449: * The optional Search-Order word set::  
  450: 
  451: The Core Words
  452: 
  453: * core-idef::                   Implementation Defined Options                   
  454: * core-ambcond::                Ambiguous Conditions                
  455: * core-other::                  Other System Documentation                  
  456: 
  457: The optional Block word set
  458: 
  459: * block-idef::                  Implementation Defined Options
  460: * block-ambcond::               Ambiguous Conditions               
  461: * block-other::                 Other System Documentation                 
  462: 
  463: The optional Double Number word set
  464: 
  465: * double-ambcond::              Ambiguous Conditions              
  466: 
  467: The optional Exception word set
  468: 
  469: * exception-idef::              Implementation Defined Options              
  470: 
  471: The optional Facility word set
  472: 
  473: * facility-idef::               Implementation Defined Options               
  474: * facility-ambcond::            Ambiguous Conditions            
  475: 
  476: The optional File-Access word set
  477: 
  478: * file-idef::                   Implementation Defined Options
  479: * file-ambcond::                Ambiguous Conditions                
  480: 
  481: The optional Floating-Point word set
  482: 
  483: * floating-idef::               Implementation Defined Options
  484: * floating-ambcond::            Ambiguous Conditions            
  485: 
  486: The optional Locals word set
  487: 
  488: * locals-idef::                 Implementation Defined Options                 
  489: * locals-ambcond::              Ambiguous Conditions              
  490: 
  491: The optional Memory-Allocation word set
  492: 
  493: * memory-idef::                 Implementation Defined Options                 
  494: 
  495: The optional Programming-Tools word set
  496: 
  497: * programming-idef::            Implementation Defined Options            
  498: * programming-ambcond::         Ambiguous Conditions         
  499: 
  500: The optional Search-Order word set
  501: 
  502: * search-idef::                 Implementation Defined Options                 
  503: * search-ambcond::              Ambiguous Conditions              
  504: 
  505: Emacs and Gforth
  506: 
  507: * Installing gforth.el::        Making Emacs aware of Forth.
  508: * Emacs Tags::                  Viewing the source of a word in Emacs.
  509: * Hilighting::                  Making Forth code look prettier.
  510: * Auto-Indentation::            Customizing auto-indentation.
  511: * Blocks Files::                Reading and writing blocks files.
  512: 
  513: Image Files
  514: 
  515: * Image Licensing Issues::      Distribution terms for images.
  516: * Image File Background::       Why have image files?
  517: * Non-Relocatable Image Files::  don't always work.
  518: * Data-Relocatable Image Files::  are better.
  519: * Fully Relocatable Image Files::  better yet.
  520: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  521: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  522: * Modifying the Startup Sequence::  and turnkey applications.
  523: 
  524: Fully Relocatable Image Files
  525: 
  526: * gforthmi::                    The normal way
  527: * cross.fs::                    The hard way
  528: 
  529: Engine
  530: 
  531: * Portability::                 
  532: * Threading::                   
  533: * Primitives::                  
  534: * Performance::                 
  535: 
  536: Threading
  537: 
  538: * Scheduling::                  
  539: * Direct or Indirect Threaded?::  
  540: * Dynamic Superinstructions::   
  541: * DOES>::                       
  542: 
  543: Primitives
  544: 
  545: * Automatic Generation::        
  546: * TOS Optimization::            
  547: * Produced code::               
  548: 
  549: Cross Compiler
  550: 
  551: * Using the Cross Compiler::    
  552: * How the Cross Compiler Works::  
  553: 
  554: Licenses
  555: 
  556: * GNU Free Documentation License::  License for copying this manual.
  557: * Copying::                     GPL (for copying this software).
  558: 
  559: @end detailmenu
  560: @end menu
  561: 
  562: @c ----------------------------------------------------------
  563: @iftex
  564: @unnumbered Preface
  565: @cindex Preface
  566: This manual documents Gforth. Some introductory material is provided for
  567: readers who are unfamiliar with Forth or who are migrating to Gforth
  568: from other Forth compilers. However, this manual is primarily a
  569: reference manual.
  570: @end iftex
  571: 
  572: @comment TODO much more blurb here.
  573: 
  574: @c ******************************************************************
  575: @node Goals, Gforth Environment, Top, Top
  576: @comment node-name,     next,           previous, up
  577: @chapter Goals of Gforth
  578: @cindex goals of the Gforth project
  579: The goal of the Gforth Project is to develop a standard model for
  580: ANS Forth. This can be split into several subgoals:
  581: 
  582: @itemize @bullet
  583: @item
  584: Gforth should conform to the ANS Forth Standard.
  585: @item
  586: It should be a model, i.e. it should define all the
  587: implementation-dependent things.
  588: @item
  589: It should become standard, i.e. widely accepted and used. This goal
  590: is the most difficult one.
  591: @end itemize
  592: 
  593: To achieve these goals Gforth should be
  594: @itemize @bullet
  595: @item
  596: Similar to previous models (fig-Forth, F83)
  597: @item
  598: Powerful. It should provide for all the things that are considered
  599: necessary today and even some that are not yet considered necessary.
  600: @item
  601: Efficient. It should not get the reputation of being exceptionally
  602: slow.
  603: @item
  604: Free.
  605: @item
  606: Available on many machines/easy to port.
  607: @end itemize
  608: 
  609: Have we achieved these goals? Gforth conforms to the ANS Forth
  610: standard. It may be considered a model, but we have not yet documented
  611: which parts of the model are stable and which parts we are likely to
  612: change. It certainly has not yet become a de facto standard, but it
  613: appears to be quite popular. It has some similarities to and some
  614: differences from previous models. It has some powerful features, but not
  615: yet everything that we envisioned. We certainly have achieved our
  616: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  617: the bar was raised when the major commercial Forth vendors switched to
  618: native code compilers.}.  It is free and available on many machines.
  619: 
  620: @c ******************************************************************
  621: @node Gforth Environment, Tutorial, Goals, Top
  622: @chapter Gforth Environment
  623: @cindex Gforth environment
  624: 
  625: Note: ultimately, the Gforth man page will be auto-generated from the
  626: material in this chapter.
  627: 
  628: @menu
  629: * Invoking Gforth::             Getting in
  630: * Leaving Gforth::              Getting out
  631: * Command-line editing::        
  632: * Environment variables::       that affect how Gforth starts up
  633: * Gforth Files::                What gets installed and where
  634: * Gforth in pipes::             
  635: * Startup speed::               When 14ms is not fast enough ...
  636: @end menu
  637: 
  638: For related information about the creation of images see @ref{Image Files}.
  639: 
  640: @comment ----------------------------------------------
  641: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  642: @section Invoking Gforth
  643: @cindex invoking Gforth
  644: @cindex running Gforth
  645: @cindex command-line options
  646: @cindex options on the command line
  647: @cindex flags on the command line
  648: 
  649: Gforth is made up of two parts; an executable ``engine'' (named
  650: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  651: will usually just say @code{gforth} -- this automatically loads the
  652: default image file @file{gforth.fi}. In many other cases the default
  653: Gforth image will be invoked like this:
  654: @example
  655: gforth [file | -e forth-code] ...
  656: @end example
  657: @noindent
  658: This interprets the contents of the files and the Forth code in the order they
  659: are given.
  660: 
  661: In addition to the @command{gforth} engine, there is also an engine
  662: called @command{gforth-fast}, which is faster, but gives less
  663: informative error messages (@pxref{Error messages}) and may catch some
  664: errors (in particular, stack underflows and integer division errors)
  665: later or not at all.  You should use it for debugged,
  666: performance-critical programs.
  667: 
  668: Moreover, there is an engine called @command{gforth-itc}, which is
  669: useful in some backwards-compatibility situations (@pxref{Direct or
  670: Indirect Threaded?}).
  671: 
  672: In general, the command line looks like this:
  673: 
  674: @example
  675: gforth[-fast] [engine options] [image options]
  676: @end example
  677: 
  678: The engine options must come before the rest of the command
  679: line. They are:
  680: 
  681: @table @code
  682: @cindex -i, command-line option
  683: @cindex --image-file, command-line option
  684: @item --image-file @i{file}
  685: @itemx -i @i{file}
  686: Loads the Forth image @i{file} instead of the default
  687: @file{gforth.fi} (@pxref{Image Files}).
  688: 
  689: @cindex --appl-image, command-line option
  690: @item --appl-image @i{file}
  691: Loads the image @i{file} and leaves all further command-line arguments
  692: to the image (instead of processing them as engine options).  This is
  693: useful for building executable application images on Unix, built with
  694: @code{gforthmi --application ...}.
  695: 
  696: @cindex --path, command-line option
  697: @cindex -p, command-line option
  698: @item --path @i{path}
  699: @itemx -p @i{path}
  700: Uses @i{path} for searching the image file and Forth source code files
  701: instead of the default in the environment variable @code{GFORTHPATH} or
  702: the path specified at installation time (e.g.,
  703: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  704: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  705: 
  706: @cindex --dictionary-size, command-line option
  707: @cindex -m, command-line option
  708: @cindex @i{size} parameters for command-line options
  709: @cindex size of the dictionary and the stacks
  710: @item --dictionary-size @i{size}
  711: @itemx -m @i{size}
  712: Allocate @i{size} space for the Forth dictionary space instead of
  713: using the default specified in the image (typically 256K). The
  714: @i{size} specification for this and subsequent options consists of
  715: an integer and a unit (e.g.,
  716: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  717: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  718: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  719: @code{e} is used.
  720: 
  721: @cindex --data-stack-size, command-line option
  722: @cindex -d, command-line option
  723: @item --data-stack-size @i{size}
  724: @itemx -d @i{size}
  725: Allocate @i{size} space for the data stack instead of using the
  726: default specified in the image (typically 16K).
  727: 
  728: @cindex --return-stack-size, command-line option
  729: @cindex -r, command-line option
  730: @item --return-stack-size @i{size}
  731: @itemx -r @i{size}
  732: Allocate @i{size} space for the return stack instead of using the
  733: default specified in the image (typically 15K).
  734: 
  735: @cindex --fp-stack-size, command-line option
  736: @cindex -f, command-line option
  737: @item --fp-stack-size @i{size}
  738: @itemx -f @i{size}
  739: Allocate @i{size} space for the floating point stack instead of
  740: using the default specified in the image (typically 15.5K). In this case
  741: the unit specifier @code{e} refers to floating point numbers.
  742: 
  743: @cindex --locals-stack-size, command-line option
  744: @cindex -l, command-line option
  745: @item --locals-stack-size @i{size}
  746: @itemx -l @i{size}
  747: Allocate @i{size} space for the locals stack instead of using the
  748: default specified in the image (typically 14.5K).
  749: 
  750: @cindex --vm-commit, command-line option
  751: @cindex overcommit memory for dictionary and stacks
  752: @cindex memory overcommit for dictionary and stacks
  753: @item --vm-commit
  754: Normally, Gforth tries to start up even if there is not enough virtual
  755: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
  756: on OSs that support it); so you can ask for a really big dictionary
  757: and/or stacks, and as long as you don't use more virtual memory than
  758: is available, everything will be fine (but if you use more, processes
  759: get killed).  With this option you just use the default allocation
  760: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
  761: means that you cannot and should not ask for as big dictionary and
  762: stacks, but once Gforth successfully starts up, out-of-memory won't
  763: kill it.
  764: 
  765: @cindex -h, command-line option
  766: @cindex --help, command-line option
  767: @item --help
  768: @itemx -h
  769: Print a message about the command-line options
  770: 
  771: @cindex -v, command-line option
  772: @cindex --version, command-line option
  773: @item --version
  774: @itemx -v
  775: Print version and exit
  776: 
  777: @cindex --debug, command-line option
  778: @item --debug
  779: Print some information useful for debugging on startup.
  780: 
  781: @cindex --offset-image, command-line option
  782: @item --offset-image
  783: Start the dictionary at a slightly different position than would be used
  784: otherwise (useful for creating data-relocatable images,
  785: @pxref{Data-Relocatable Image Files}).
  786: 
  787: @cindex --no-offset-im, command-line option
  788: @item --no-offset-im
  789: Start the dictionary at the normal position.
  790: 
  791: @cindex --clear-dictionary, command-line option
  792: @item --clear-dictionary
  793: Initialize all bytes in the dictionary to 0 before loading the image
  794: (@pxref{Data-Relocatable Image Files}).
  795: 
  796: @cindex --die-on-signal, command-line-option
  797: @item --die-on-signal
  798: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  799: or the segmentation violation SIGSEGV) by translating it into a Forth
  800: @code{THROW}. With this option, Gforth exits if it receives such a
  801: signal. This option is useful when the engine and/or the image might be
  802: severely broken (such that it causes another signal before recovering
  803: from the first); this option avoids endless loops in such cases.
  804: 
  805: @cindex --no-dynamic, command-line option
  806: @cindex --dynamic, command-line option
  807: @item --no-dynamic
  808: @item --dynamic
  809: Disable or enable dynamic superinstructions with replication
  810: (@pxref{Dynamic Superinstructions}).
  811: 
  812: @cindex --no-super, command-line option
  813: @item --no-super
  814: Disable dynamic superinstructions, use just dynamic replication; this is
  815: useful if you want to patch threaded code (@pxref{Dynamic
  816: Superinstructions}).
  817: 
  818: @cindex --ss-number, command-line option
  819: @item --ss-number=@var{N}
  820: Use only the first @var{N} static superinstructions compiled into the
  821: engine (default: use them all; note that only @code{gforth-fast} has
  822: any).  This option is useful for measuring the performance impact of
  823: static superinstructions.
  824: 
  825: @cindex --ss-min-..., command-line options
  826: @item --ss-min-codesize
  827: @item --ss-min-ls
  828: @item --ss-min-lsu
  829: @item --ss-min-nexts
  830: Use specified metric for determining the cost of a primitive or static
  831: superinstruction for static superinstruction selection.  @code{Codesize}
  832: is the native code size of the primive or static superinstruction,
  833: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  834: loads, stores, and updates, and @code{nexts} is the number of dispatches
  835: (not taking dynamic superinstructions into account), i.e. every
  836: primitive or static superinstruction has cost 1. Default:
  837: @code{codesize} if you use dynamic code generation, otherwise
  838: @code{nexts}.
  839: 
  840: @cindex --ss-greedy, command-line option
  841: @item --ss-greedy
  842: This option is useful for measuring the performance impact of static
  843: superinstructions.  By default, an optimal shortest-path algorithm is
  844: used for selecting static superinstructions.  With @option{--ss-greedy}
  845: this algorithm is modified to assume that anything after the static
  846: superinstruction currently under consideration is not combined into
  847: static superinstructions.  With @option{--ss-min-nexts} this produces
  848: the same result as a greedy algorithm that always selects the longest
  849: superinstruction available at the moment.  E.g., if there are
  850: superinstructions AB and BCD, then for the sequence A B C D the optimal
  851: algorithm will select A BCD and the greedy algorithm will select AB C D.
  852: 
  853: @cindex --print-metrics, command-line option
  854: @item --print-metrics
  855: Prints some metrics used during static superinstruction selection:
  856: @code{code size} is the actual size of the dynamically generated code.
  857: @code{Metric codesize} is the sum of the codesize metrics as seen by
  858: static superinstruction selection; there is a difference from @code{code
  859: size}, because not all primitives and static superinstructions are
  860: compiled into dynamically generated code, and because of markers.  The
  861: other metrics correspond to the @option{ss-min-...} options.  This
  862: option is useful for evaluating the effects of the @option{--ss-...}
  863: options.
  864: 
  865: @end table
  866: 
  867: @cindex loading files at startup
  868: @cindex executing code on startup
  869: @cindex batch processing with Gforth
  870: As explained above, the image-specific command-line arguments for the
  871: default image @file{gforth.fi} consist of a sequence of filenames and
  872: @code{-e @var{forth-code}} options that are interpreted in the sequence
  873: in which they are given. The @code{-e @var{forth-code}} or
  874: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  875: option takes only one argument; if you want to evaluate more Forth
  876: words, you have to quote them or use @code{-e} several times. To exit
  877: after processing the command line (instead of entering interactive mode)
  878: append @code{-e bye} to the command line.  You can also process the
  879: command-line arguments with a Forth program (@pxref{OS command line
  880: arguments}).
  881: 
  882: @cindex versions, invoking other versions of Gforth
  883: If you have several versions of Gforth installed, @code{gforth} will
  884: invoke the version that was installed last. @code{gforth-@i{version}}
  885: invokes a specific version. If your environment contains the variable
  886: @code{GFORTHPATH}, you may want to override it by using the
  887: @code{--path} option.
  888: 
  889: Not yet implemented:
  890: On startup the system first executes the system initialization file
  891: (unless the option @code{--no-init-file} is given; note that the system
  892: resulting from using this option may not be ANS Forth conformant). Then
  893: the user initialization file @file{.gforth.fs} is executed, unless the
  894: option @code{--no-rc} is given; this file is searched for in @file{.},
  895: then in @file{~}, then in the normal path (see above).
  896: 
  897: 
  898: 
  899: @comment ----------------------------------------------
  900: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  901: @section Leaving Gforth
  902: @cindex Gforth - leaving
  903: @cindex leaving Gforth
  904: 
  905: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  906: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  907: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  908: data are discarded.  For ways of saving the state of the system before
  909: leaving Gforth see @ref{Image Files}.
  910: 
  911: doc-bye
  912: 
  913: 
  914: @comment ----------------------------------------------
  915: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  916: @section Command-line editing
  917: @cindex command-line editing
  918: 
  919: Gforth maintains a history file that records every line that you type to
  920: the text interpreter. This file is preserved between sessions, and is
  921: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  922: repeatedly you can recall successively older commands from this (or
  923: previous) session(s). The full list of command-line editing facilities is:
  924: 
  925: @itemize @bullet
  926: @item
  927: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  928: commands from the history buffer.
  929: @item
  930: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  931: from the history buffer.
  932: @item
  933: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  934: @item
  935: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  936: @item
  937: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  938: closing up the line.
  939: @item
  940: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  941: @item
  942: @kbd{Ctrl-a} to move the cursor to the start of the line.
  943: @item
  944: @kbd{Ctrl-e} to move the cursor to the end of the line.
  945: @item
  946: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  947: line.
  948: @item
  949: @key{TAB} to step through all possible full-word completions of the word
  950: currently being typed.
  951: @item
  952: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  953: using @code{bye}). 
  954: @item
  955: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  956: character under the cursor.
  957: @end itemize
  958: 
  959: When editing, displayable characters are inserted to the left of the
  960: cursor position; the line is always in ``insert'' (as opposed to
  961: ``overstrike'') mode.
  962: 
  963: @cindex history file
  964: @cindex @file{.gforth-history}
  965: On Unix systems, the history file is @file{~/.gforth-history} by
  966: default@footnote{i.e. it is stored in the user's home directory.}. You
  967: can find out the name and location of your history file using:
  968: 
  969: @example 
  970: history-file type \ Unix-class systems
  971: 
  972: history-file type \ Other systems
  973: history-dir  type
  974: @end example
  975: 
  976: If you enter long definitions by hand, you can use a text editor to
  977: paste them out of the history file into a Forth source file for reuse at
  978: a later time.
  979: 
  980: Gforth never trims the size of the history file, so you should do this
  981: periodically, if necessary.
  982: 
  983: @comment this is all defined in history.fs
  984: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  985: @comment chosen?
  986: 
  987: 
  988: @comment ----------------------------------------------
  989: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  990: @section Environment variables
  991: @cindex environment variables
  992: 
  993: Gforth uses these environment variables:
  994: 
  995: @itemize @bullet
  996: @item
  997: @cindex @code{GFORTHHIST} -- environment variable
  998: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  999: open/create the history file, @file{.gforth-history}. Default:
 1000: @code{$HOME}.
 1001: 
 1002: @item
 1003: @cindex @code{GFORTHPATH} -- environment variable
 1004: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1005: for Forth source-code files.
 1006: 
 1007: @item
 1008: @cindex @code{LANG} -- environment variable
 1009: @code{LANG} -- see @code{LC_CTYPE}
 1010: 
 1011: @item
 1012: @cindex @code{LC_ALL} -- environment variable
 1013: @code{LC_ALL} -- see @code{LC_CTYPE}
 1014: 
 1015: @item
 1016: @cindex @code{LC_CTYPE} -- environment variable
 1017: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
 1018: startup, Gforth uses the UTF-8 encoding for strings internally and
 1019: expects its input and produces its output in UTF-8 encoding, otherwise
 1020: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
 1021: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
 1022: that is unset, in @code{LANG}.
 1023: 
 1024: @item
 1025: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
 1026: 
 1027: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
 1028: of @code{system} before passing it to C's @code{system()}.  Default:
 1029: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
 1030: and the command are directly concatenated, so if a space between them is
 1031: necessary, append it to the prefix.
 1032: 
 1033: @item
 1034: @cindex @code{GFORTH} -- environment variable
 1035: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1036: 
 1037: @item
 1038: @cindex @code{GFORTHD} -- environment variable
 1039: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1040: 
 1041: @item
 1042: @cindex @code{TMP}, @code{TEMP} - environment variable
 1043: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1044: location for the history file.
 1045: @end itemize
 1046: 
 1047: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1048: @comment mentioning these.
 1049: 
 1050: All the Gforth environment variables default to sensible values if they
 1051: are not set.
 1052: 
 1053: 
 1054: @comment ----------------------------------------------
 1055: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1056: @section Gforth files
 1057: @cindex Gforth files
 1058: 
 1059: When you install Gforth on a Unix system, it installs files in these
 1060: locations by default:
 1061: 
 1062: @itemize @bullet
 1063: @item
 1064: @file{/usr/local/bin/gforth}
 1065: @item
 1066: @file{/usr/local/bin/gforthmi}
 1067: @item
 1068: @file{/usr/local/man/man1/gforth.1} - man page.
 1069: @item
 1070: @file{/usr/local/info} - the Info version of this manual.
 1071: @item
 1072: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1073: @item
 1074: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1075: @item
 1076: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1077: @item
 1078: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1079: @end itemize
 1080: 
 1081: You can select different places for installation by using
 1082: @code{configure} options (listed with @code{configure --help}).
 1083: 
 1084: @comment ----------------------------------------------
 1085: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1086: @section Gforth in pipes
 1087: @cindex pipes, Gforth as part of
 1088: 
 1089: Gforth can be used in pipes created elsewhere (described here).  It can
 1090: also create pipes on its own (@pxref{Pipes}).
 1091: 
 1092: @cindex input from pipes
 1093: If you pipe into Gforth, your program should read with @code{read-file}
 1094: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1095: @code{Key} does not recognize the end of input.  Words like
 1096: @code{accept} echo the input and are therefore usually not useful for
 1097: reading from a pipe.  You have to invoke the Forth program with an OS
 1098: command-line option, as you have no chance to use the Forth command line
 1099: (the text interpreter would try to interpret the pipe input).
 1100: 
 1101: @cindex output in pipes
 1102: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1103: 
 1104: @cindex silent exiting from Gforth
 1105: When you write to a pipe that has been closed at the other end, Gforth
 1106: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1107: into the exception @code{broken-pipe-error}.  If your application does
 1108: not catch that exception, the system catches it and exits, usually
 1109: silently (unless you were working on the Forth command line; then it
 1110: prints an error message and exits).  This is usually the desired
 1111: behaviour.
 1112: 
 1113: If you do not like this behaviour, you have to catch the exception
 1114: yourself, and react to it.
 1115: 
 1116: Here's an example of an invocation of Gforth that is usable in a pipe:
 1117: 
 1118: @example
 1119: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1120:  type repeat ; foo bye"
 1121: @end example
 1122: 
 1123: This example just copies the input verbatim to the output.  A very
 1124: simple pipe containing this example looks like this:
 1125: 
 1126: @example
 1127: cat startup.fs |
 1128: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1129:  type repeat ; foo bye"|
 1130: head
 1131: @end example
 1132: 
 1133: @cindex stderr and pipes
 1134: Pipes involving Gforth's @code{stderr} output do not work.
 1135: 
 1136: @comment ----------------------------------------------
 1137: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1138: @section Startup speed
 1139: @cindex Startup speed
 1140: @cindex speed, startup
 1141: 
 1142: If Gforth is used for CGI scripts or in shell scripts, its startup
 1143: speed may become a problem.  On a 3GHz Core 2 Duo E8400 under 64-bit
 1144: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
 1145: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
 1146: with about 3.4ms user time and 1.2ms system time, because it subsumes
 1147: some of the options discussed below).
 1148: 
 1149: If startup speed is a problem, you may consider the following ways to
 1150: improve it; or you may consider ways to reduce the number of startups
 1151: (for example, by using Fast-CGI).  Note that the first steps below
 1152: improve the startup time at the cost of run-time (including
 1153: compile-time), so whether they are profitable depends on the balance
 1154: of these times in your application.
 1155: 
 1156: An easy step that influences Gforth startup speed is the use of a
 1157: number of options that increase run-time, but decrease image-loading
 1158: time.
 1159: 
 1160: The first of these that you should try is @code{--ss-number=0
 1161: --ss-states=1} because this option buys relatively little run-time
 1162: speedup and costs quite a bit of time at startup.  @code{gforth-fast
 1163: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
 1164: system time.
 1165: 
 1166: The next option is @code{--no-dynamic} which has a substantial impact
 1167: on run-time (about a factor of 2 on several platforms), but still
 1168: makes startup speed a little faster: @code{gforth-fast --ss-number=0
 1169: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
 1170: system time.
 1171: 
 1172: The next step to improve startup speed is to use a data-relocatable
 1173: image (@pxref{Data-Relocatable Image Files}).  This avoids the
 1174: relocation cost for the code in the image (but not for the data).
 1175: Note that the image is then specific to the particular binary you are
 1176: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
 1177: the particular build).  You create the data-relocatable image that
 1178: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
 1179: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
 1180: required here or the image will not work).  And you run it with
 1181: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
 1182: above don't matter here, because they only come into play on
 1183: relocatable code).  @code{gforth-fast -i gforthdr.fi -e bye} takes
 1184: about 1.1ms user and 1.2ms system time.
 1185: 
 1186: One step further is to avoid all relocation cost and part of the
 1187: copy-on-write cost through using a non-relocatable image
 1188: (@pxref{Non-Relocatable Image Files}).  However, this has the
 1189: disadvantage that it does not work on operating systems with address
 1190: space randomization (the default in, e.g., Linux nowadays), or if the
 1191: dictionary moves for any other reason (e.g., because of a change of
 1192: the OS kernel or an updated library), so we cannot really recommend
 1193: it.  You create a non-relocatable image with @code{gforth-fast
 1194: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
 1195: is required here, too).  And you run it with @code{gforth-fast -i
 1196: gforthnr.fi ... -e bye} (again the flags discussed above don't
 1197: matter).  @code{gforth-fast -i gforthdr.fi -e bye} takes
 1198: about 0.9ms user and 0.9ms system time.
 1199: 
 1200: If the script you want to execute contains a significant amount of
 1201: code, it may be profitable to compile it into the image to avoid the
 1202: cost of compiling it at startup time.
 1203: 
 1204: @c ******************************************************************
 1205: @node Tutorial, Introduction, Gforth Environment, Top
 1206: @chapter Forth Tutorial
 1207: @cindex Tutorial
 1208: @cindex Forth Tutorial
 1209: 
 1210: @c Topics from nac's Introduction that could be mentioned:
 1211: @c press <ret> after each line
 1212: @c Prompt
 1213: @c numbers vs. words in dictionary on text interpretation
 1214: @c what happens on redefinition
 1215: @c parsing words (in particular, defining words)
 1216: 
 1217: The difference of this chapter from the Introduction
 1218: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1219: be used while sitting in front of a computer, and covers much more
 1220: material, but does not explain how the Forth system works.
 1221: 
 1222: This tutorial can be used with any ANS-compliant Forth; any
 1223: Gforth-specific features are marked as such and you can skip them if
 1224: you work with another Forth.  This tutorial does not explain all
 1225: features of Forth, just enough to get you started and give you some
 1226: ideas about the facilities available in Forth.  Read the rest of the
 1227: manual when you are through this.
 1228: 
 1229: The intended way to use this tutorial is that you work through it while
 1230: sitting in front of the console, take a look at the examples and predict
 1231: what they will do, then try them out; if the outcome is not as expected,
 1232: find out why (e.g., by trying out variations of the example), so you
 1233: understand what's going on.  There are also some assignments that you
 1234: should solve.
 1235: 
 1236: This tutorial assumes that you have programmed before and know what,
 1237: e.g., a loop is.
 1238: 
 1239: @c !! explain compat library
 1240: 
 1241: @menu
 1242: * Starting Gforth Tutorial::    
 1243: * Syntax Tutorial::             
 1244: * Crash Course Tutorial::       
 1245: * Stack Tutorial::              
 1246: * Arithmetics Tutorial::        
 1247: * Stack Manipulation Tutorial::  
 1248: * Using files for Forth code Tutorial::  
 1249: * Comments Tutorial::           
 1250: * Colon Definitions Tutorial::  
 1251: * Decompilation Tutorial::      
 1252: * Stack-Effect Comments Tutorial::  
 1253: * Types Tutorial::              
 1254: * Factoring Tutorial::          
 1255: * Designing the stack effect Tutorial::  
 1256: * Local Variables Tutorial::    
 1257: * Conditional execution Tutorial::  
 1258: * Flags and Comparisons Tutorial::  
 1259: * General Loops Tutorial::      
 1260: * Counted loops Tutorial::      
 1261: * Recursion Tutorial::          
 1262: * Leaving definitions or loops Tutorial::  
 1263: * Return Stack Tutorial::       
 1264: * Memory Tutorial::             
 1265: * Characters and Strings Tutorial::  
 1266: * Alignment Tutorial::          
 1267: * Floating Point Tutorial::     
 1268: * Files Tutorial::              
 1269: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1270: * Execution Tokens Tutorial::   
 1271: * Exceptions Tutorial::         
 1272: * Defining Words Tutorial::     
 1273: * Arrays and Records Tutorial::  
 1274: * POSTPONE Tutorial::           
 1275: * Literal Tutorial::            
 1276: * Advanced macros Tutorial::    
 1277: * Compilation Tokens Tutorial::  
 1278: * Wordlists and Search Order Tutorial::  
 1279: @end menu
 1280: 
 1281: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1282: @section Starting Gforth
 1283: @cindex starting Gforth tutorial
 1284: You can start Gforth by typing its name:
 1285: 
 1286: @example
 1287: gforth
 1288: @end example
 1289: 
 1290: That puts you into interactive mode; you can leave Gforth by typing
 1291: @code{bye}.  While in Gforth, you can edit the command line and access
 1292: the command line history with cursor keys, similar to bash.
 1293: 
 1294: 
 1295: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1296: @section Syntax
 1297: @cindex syntax tutorial
 1298: 
 1299: A @dfn{word} is a sequence of arbitrary characters (except white
 1300: space).  Words are separated by white space.  E.g., each of the
 1301: following lines contains exactly one word:
 1302: 
 1303: @example
 1304: word
 1305: !@@#$%^&*()
 1306: 1234567890
 1307: 5!a
 1308: @end example
 1309: 
 1310: A frequent beginner's error is to leave out necessary white space,
 1311: resulting in an error like @samp{Undefined word}; so if you see such an
 1312: error, check if you have put spaces wherever necessary.
 1313: 
 1314: @example
 1315: ." hello, world" \ correct
 1316: ."hello, world"  \ gives an "Undefined word" error
 1317: @end example
 1318: 
 1319: Gforth and most other Forth systems ignore differences in case (they are
 1320: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1321: your system is case-sensitive, you may have to type all the examples
 1322: given here in upper case.
 1323: 
 1324: 
 1325: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1326: @section Crash Course
 1327: 
 1328: Forth does not prevent you from shooting yourself in the foot.  Let's
 1329: try a few ways to crash Gforth:
 1330: 
 1331: @example
 1332: 0 0 !
 1333: here execute
 1334: ' catch >body 20 erase abort
 1335: ' (quit) >body 20 erase
 1336: @end example
 1337: 
 1338: The last two examples are guaranteed to destroy important parts of
 1339: Gforth (and most other systems), so you better leave Gforth afterwards
 1340: (if it has not finished by itself).  On some systems you may have to
 1341: kill gforth from outside (e.g., in Unix with @code{kill}).
 1342: 
 1343: You will find out later what these lines do and then you will get an
 1344: idea why they produce crashes.
 1345: 
 1346: Now that you know how to produce crashes (and that there's not much to
 1347: them), let's learn how to produce meaningful programs.
 1348: 
 1349: 
 1350: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1351: @section Stack
 1352: @cindex stack tutorial
 1353: 
 1354: The most obvious feature of Forth is the stack.  When you type in a
 1355: number, it is pushed on the stack.  You can display the contents of the
 1356: stack with @code{.s}.
 1357: 
 1358: @example
 1359: 1 2 .s
 1360: 3 .s
 1361: @end example
 1362: 
 1363: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1364: appear in @code{.s} output as they appeared in the input.
 1365: 
 1366: You can print the top element of the stack with @code{.}.
 1367: 
 1368: @example
 1369: 1 2 3 . . .
 1370: @end example
 1371: 
 1372: In general, words consume their stack arguments (@code{.s} is an
 1373: exception).
 1374: 
 1375: @quotation Assignment
 1376: What does the stack contain after @code{5 6 7 .}?
 1377: @end quotation
 1378: 
 1379: 
 1380: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1381: @section Arithmetics
 1382: @cindex arithmetics tutorial
 1383: 
 1384: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1385: operate on the top two stack items:
 1386: 
 1387: @example
 1388: 2 2 .s
 1389: + .s
 1390: .
 1391: 2 1 - .
 1392: 7 3 mod .
 1393: @end example
 1394: 
 1395: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1396: as in the corresponding infix expression (this is generally the case in
 1397: Forth).
 1398: 
 1399: Parentheses are superfluous (and not available), because the order of
 1400: the words unambiguously determines the order of evaluation and the
 1401: operands:
 1402: 
 1403: @example
 1404: 3 4 + 5 * .
 1405: 3 4 5 * + .
 1406: @end example
 1407: 
 1408: @quotation Assignment
 1409: What are the infix expressions corresponding to the Forth code above?
 1410: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1411: known as Postfix or RPN (Reverse Polish Notation).}.
 1412: @end quotation
 1413: 
 1414: To change the sign, use @code{negate}:
 1415: 
 1416: @example
 1417: 2 negate .
 1418: @end example
 1419: 
 1420: @quotation Assignment
 1421: Convert -(-3)*4-5 to Forth.
 1422: @end quotation
 1423: 
 1424: @code{/mod} performs both @code{/} and @code{mod}.
 1425: 
 1426: @example
 1427: 7 3 /mod . .
 1428: @end example
 1429: 
 1430: Reference: @ref{Arithmetic}.
 1431: 
 1432: 
 1433: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1434: @section Stack Manipulation
 1435: @cindex stack manipulation tutorial
 1436: 
 1437: Stack manipulation words rearrange the data on the stack.
 1438: 
 1439: @example
 1440: 1 .s drop .s
 1441: 1 .s dup .s drop drop .s
 1442: 1 2 .s over .s drop drop drop
 1443: 1 2 .s swap .s drop drop
 1444: 1 2 3 .s rot .s drop drop drop
 1445: @end example
 1446: 
 1447: These are the most important stack manipulation words.  There are also
 1448: variants that manipulate twice as many stack items:
 1449: 
 1450: @example
 1451: 1 2 3 4 .s 2swap .s 2drop 2drop
 1452: @end example
 1453: 
 1454: Two more stack manipulation words are:
 1455: 
 1456: @example
 1457: 1 2 .s nip .s drop
 1458: 1 2 .s tuck .s 2drop drop
 1459: @end example
 1460: 
 1461: @quotation Assignment
 1462: Replace @code{nip} and @code{tuck} with combinations of other stack
 1463: manipulation words.
 1464: 
 1465: @example
 1466: Given:          How do you get:
 1467: 1 2 3           3 2 1           
 1468: 1 2 3           1 2 3 2                 
 1469: 1 2 3           1 2 3 3                 
 1470: 1 2 3           1 3 3           
 1471: 1 2 3           2 1 3           
 1472: 1 2 3 4         4 3 2 1         
 1473: 1 2 3           1 2 3 1 2 3             
 1474: 1 2 3 4         1 2 3 4 1 2             
 1475: 1 2 3
 1476: 1 2 3           1 2 3 4                 
 1477: 1 2 3           1 3             
 1478: @end example
 1479: @end quotation
 1480: 
 1481: @example
 1482: 5 dup * .
 1483: @end example
 1484: 
 1485: @quotation Assignment
 1486: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1487: Write a piece of Forth code that expects two numbers on the stack
 1488: (@var{a} and @var{b}, with @var{b} on top) and computes
 1489: @code{(a-b)(a+1)}.
 1490: @end quotation
 1491: 
 1492: Reference: @ref{Stack Manipulation}.
 1493: 
 1494: 
 1495: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1496: @section Using files for Forth code
 1497: @cindex loading Forth code, tutorial
 1498: @cindex files containing Forth code, tutorial
 1499: 
 1500: While working at the Forth command line is convenient for one-line
 1501: examples and short one-off code, you probably want to store your source
 1502: code in files for convenient editing and persistence.  You can use your
 1503: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1504: Gforth}) to create @var{file.fs} and use
 1505: 
 1506: @example
 1507: s" @var{file.fs}" included
 1508: @end example
 1509: 
 1510: to load it into your Forth system.  The file name extension I use for
 1511: Forth files is @samp{.fs}.
 1512: 
 1513: You can easily start Gforth with some files loaded like this:
 1514: 
 1515: @example
 1516: gforth @var{file1.fs} @var{file2.fs}
 1517: @end example
 1518: 
 1519: If an error occurs during loading these files, Gforth terminates,
 1520: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1521: a Gforth command line.  Starting the Forth system every time gives you a
 1522: clean start every time, without interference from the results of earlier
 1523: tries.
 1524: 
 1525: I often put all the tests in a file, then load the code and run the
 1526: tests with
 1527: 
 1528: @example
 1529: gforth @var{code.fs} @var{tests.fs} -e bye
 1530: @end example
 1531: 
 1532: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1533: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1534: restart this command without ado.
 1535: 
 1536: The advantage of this approach is that the tests can be repeated easily
 1537: every time the program ist changed, making it easy to catch bugs
 1538: introduced by the change.
 1539: 
 1540: Reference: @ref{Forth source files}.
 1541: 
 1542: 
 1543: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1544: @section Comments
 1545: @cindex comments tutorial
 1546: 
 1547: @example
 1548: \ That's a comment; it ends at the end of the line
 1549: ( Another comment; it ends here: )  .s
 1550: @end example
 1551: 
 1552: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1553: separated with white space from the following text.
 1554: 
 1555: @example
 1556: \This gives an "Undefined word" error
 1557: @end example
 1558: 
 1559: The first @code{)} ends a comment started with @code{(}, so you cannot
 1560: nest @code{(}-comments; and you cannot comment out text containing a
 1561: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1562: avoid @code{)} in word names.}.
 1563: 
 1564: I use @code{\}-comments for descriptive text and for commenting out code
 1565: of one or more line; I use @code{(}-comments for describing the stack
 1566: effect, the stack contents, or for commenting out sub-line pieces of
 1567: code.
 1568: 
 1569: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1570: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1571: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1572: with @kbd{M-q}.
 1573: 
 1574: Reference: @ref{Comments}.
 1575: 
 1576: 
 1577: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1578: @section Colon Definitions
 1579: @cindex colon definitions, tutorial
 1580: @cindex definitions, tutorial
 1581: @cindex procedures, tutorial
 1582: @cindex functions, tutorial
 1583: 
 1584: are similar to procedures and functions in other programming languages.
 1585: 
 1586: @example
 1587: : squared ( n -- n^2 )
 1588:    dup * ;
 1589: 5 squared .
 1590: 7 squared .
 1591: @end example
 1592: 
 1593: @code{:} starts the colon definition; its name is @code{squared}.  The
 1594: following comment describes its stack effect.  The words @code{dup *}
 1595: are not executed, but compiled into the definition.  @code{;} ends the
 1596: colon definition.
 1597: 
 1598: The newly-defined word can be used like any other word, including using
 1599: it in other definitions:
 1600: 
 1601: @example
 1602: : cubed ( n -- n^3 )
 1603:    dup squared * ;
 1604: -5 cubed .
 1605: : fourth-power ( n -- n^4 )
 1606:    squared squared ;
 1607: 3 fourth-power .
 1608: @end example
 1609: 
 1610: @quotation Assignment
 1611: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1612: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1613: test your tests on the originals first).  Don't let the
 1614: @samp{redefined}-Messages spook you, they are just warnings.
 1615: @end quotation
 1616: 
 1617: Reference: @ref{Colon Definitions}.
 1618: 
 1619: 
 1620: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1621: @section Decompilation
 1622: @cindex decompilation tutorial
 1623: @cindex see tutorial
 1624: 
 1625: You can decompile colon definitions with @code{see}:
 1626: 
 1627: @example
 1628: see squared
 1629: see cubed
 1630: @end example
 1631: 
 1632: In Gforth @code{see} shows you a reconstruction of the source code from
 1633: the executable code.  Informations that were present in the source, but
 1634: not in the executable code, are lost (e.g., comments).
 1635: 
 1636: You can also decompile the predefined words:
 1637: 
 1638: @example
 1639: see .
 1640: see +
 1641: @end example
 1642: 
 1643: 
 1644: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1645: @section Stack-Effect Comments
 1646: @cindex stack-effect comments, tutorial
 1647: @cindex --, tutorial
 1648: By convention the comment after the name of a definition describes the
 1649: stack effect: The part in front of the @samp{--} describes the state of
 1650: the stack before the execution of the definition, i.e., the parameters
 1651: that are passed into the colon definition; the part behind the @samp{--}
 1652: is the state of the stack after the execution of the definition, i.e.,
 1653: the results of the definition.  The stack comment only shows the top
 1654: stack items that the definition accesses and/or changes.
 1655: 
 1656: You should put a correct stack effect on every definition, even if it is
 1657: just @code{( -- )}.  You should also add some descriptive comment to
 1658: more complicated words (I usually do this in the lines following
 1659: @code{:}).  If you don't do this, your code becomes unreadable (because
 1660: you have to work through every definition before you can understand
 1661: any).
 1662: 
 1663: @quotation Assignment
 1664: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1665: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1666: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1667: are done, you can compare your stack effects to those in this manual
 1668: (@pxref{Word Index}).
 1669: @end quotation
 1670: 
 1671: Sometimes programmers put comments at various places in colon
 1672: definitions that describe the contents of the stack at that place (stack
 1673: comments); i.e., they are like the first part of a stack-effect
 1674: comment. E.g.,
 1675: 
 1676: @example
 1677: : cubed ( n -- n^3 )
 1678:    dup squared  ( n n^2 ) * ;
 1679: @end example
 1680: 
 1681: In this case the stack comment is pretty superfluous, because the word
 1682: is simple enough.  If you think it would be a good idea to add such a
 1683: comment to increase readability, you should also consider factoring the
 1684: word into several simpler words (@pxref{Factoring Tutorial,,
 1685: Factoring}), which typically eliminates the need for the stack comment;
 1686: however, if you decide not to refactor it, then having such a comment is
 1687: better than not having it.
 1688: 
 1689: The names of the stack items in stack-effect and stack comments in the
 1690: standard, in this manual, and in many programs specify the type through
 1691: a type prefix, similar to Fortran and Hungarian notation.  The most
 1692: frequent prefixes are:
 1693: 
 1694: @table @code
 1695: @item n
 1696: signed integer
 1697: @item u
 1698: unsigned integer
 1699: @item c
 1700: character
 1701: @item f
 1702: Boolean flags, i.e. @code{false} or @code{true}.
 1703: @item a-addr,a-
 1704: Cell-aligned address
 1705: @item c-addr,c-
 1706: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1707: @item xt
 1708: Execution token, same size as Cell
 1709: @item w,x
 1710: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1711: 16 bits (depending on your platform and Forth system). A cell is more
 1712: commonly known as machine word, but the term @emph{word} already means
 1713: something different in Forth.
 1714: @item d
 1715: signed double-cell integer
 1716: @item ud
 1717: unsigned double-cell integer
 1718: @item r
 1719: Float (on the FP stack)
 1720: @end table
 1721: 
 1722: You can find a more complete list in @ref{Notation}.
 1723: 
 1724: @quotation Assignment
 1725: Write stack-effect comments for all definitions you have written up to
 1726: now.
 1727: @end quotation
 1728: 
 1729: 
 1730: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1731: @section Types
 1732: @cindex types tutorial
 1733: 
 1734: In Forth the names of the operations are not overloaded; so similar
 1735: operations on different types need different names; e.g., @code{+} adds
 1736: integers, and you have to use @code{f+} to add floating-point numbers.
 1737: The following prefixes are often used for related operations on
 1738: different types:
 1739: 
 1740: @table @code
 1741: @item (none)
 1742: signed integer
 1743: @item u
 1744: unsigned integer
 1745: @item c
 1746: character
 1747: @item d
 1748: signed double-cell integer
 1749: @item ud, du
 1750: unsigned double-cell integer
 1751: @item 2
 1752: two cells (not-necessarily double-cell numbers)
 1753: @item m, um
 1754: mixed single-cell and double-cell operations
 1755: @item f
 1756: floating-point (note that in stack comments @samp{f} represents flags,
 1757: and @samp{r} represents FP numbers; also, you need to include the
 1758: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
 1759: @end table
 1760: 
 1761: If there are no differences between the signed and the unsigned variant
 1762: (e.g., for @code{+}), there is only the prefix-less variant.
 1763: 
 1764: Forth does not perform type checking, neither at compile time, nor at
 1765: run time.  If you use the wrong operation, the data are interpreted
 1766: incorrectly:
 1767: 
 1768: @example
 1769: -1 u.
 1770: @end example
 1771: 
 1772: If you have only experience with type-checked languages until now, and
 1773: have heard how important type-checking is, don't panic!  In my
 1774: experience (and that of other Forthers), type errors in Forth code are
 1775: usually easy to find (once you get used to it), the increased vigilance
 1776: of the programmer tends to catch some harder errors in addition to most
 1777: type errors, and you never have to work around the type system, so in
 1778: most situations the lack of type-checking seems to be a win (projects to
 1779: add type checking to Forth have not caught on).
 1780: 
 1781: 
 1782: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1783: @section Factoring
 1784: @cindex factoring tutorial
 1785: 
 1786: If you try to write longer definitions, you will soon find it hard to
 1787: keep track of the stack contents.  Therefore, good Forth programmers
 1788: tend to write only short definitions (e.g., three lines).  The art of
 1789: finding meaningful short definitions is known as factoring (as in
 1790: factoring polynomials).
 1791: 
 1792: Well-factored programs offer additional advantages: smaller, more
 1793: general words, are easier to test and debug and can be reused more and
 1794: better than larger, specialized words.
 1795: 
 1796: So, if you run into difficulties with stack management, when writing
 1797: code, try to define meaningful factors for the word, and define the word
 1798: in terms of those.  Even if a factor contains only two words, it is
 1799: often helpful.
 1800: 
 1801: Good factoring is not easy, and it takes some practice to get the knack
 1802: for it; but even experienced Forth programmers often don't find the
 1803: right solution right away, but only when rewriting the program.  So, if
 1804: you don't come up with a good solution immediately, keep trying, don't
 1805: despair.
 1806: 
 1807: @c example !!
 1808: 
 1809: 
 1810: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1811: @section Designing the stack effect
 1812: @cindex Stack effect design, tutorial
 1813: @cindex design of stack effects, tutorial
 1814: 
 1815: In other languages you can use an arbitrary order of parameters for a
 1816: function; and since there is only one result, you don't have to deal with
 1817: the order of results, either.
 1818: 
 1819: In Forth (and other stack-based languages, e.g., PostScript) the
 1820: parameter and result order of a definition is important and should be
 1821: designed well.  The general guideline is to design the stack effect such
 1822: that the word is simple to use in most cases, even if that complicates
 1823: the implementation of the word.  Some concrete rules are:
 1824: 
 1825: @itemize @bullet
 1826: 
 1827: @item
 1828: Words consume all of their parameters (e.g., @code{.}).
 1829: 
 1830: @item
 1831: If there is a convention on the order of parameters (e.g., from
 1832: mathematics or another programming language), stick with it (e.g.,
 1833: @code{-}).
 1834: 
 1835: @item
 1836: If one parameter usually requires only a short computation (e.g., it is
 1837: a constant), pass it on the top of the stack.  Conversely, parameters
 1838: that usually require a long sequence of code to compute should be passed
 1839: as the bottom (i.e., first) parameter.  This makes the code easier to
 1840: read, because the reader does not need to keep track of the bottom item
 1841: through a long sequence of code (or, alternatively, through stack
 1842: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1843: address on top of the stack because it is usually simpler to compute
 1844: than the stored value (often the address is just a variable).
 1845: 
 1846: @item
 1847: Similarly, results that are usually consumed quickly should be returned
 1848: on the top of stack, whereas a result that is often used in long
 1849: computations should be passed as bottom result.  E.g., the file words
 1850: like @code{open-file} return the error code on the top of stack, because
 1851: it is usually consumed quickly by @code{throw}; moreover, the error code
 1852: has to be checked before doing anything with the other results.
 1853: 
 1854: @end itemize
 1855: 
 1856: These rules are just general guidelines, don't lose sight of the overall
 1857: goal to make the words easy to use.  E.g., if the convention rule
 1858: conflicts with the computation-length rule, you might decide in favour
 1859: of the convention if the word will be used rarely, and in favour of the
 1860: computation-length rule if the word will be used frequently (because
 1861: with frequent use the cost of breaking the computation-length rule would
 1862: be quite high, and frequent use makes it easier to remember an
 1863: unconventional order).
 1864: 
 1865: @c example !! structure package
 1866: 
 1867: 
 1868: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1869: @section Local Variables
 1870: @cindex local variables, tutorial
 1871: 
 1872: You can define local variables (@emph{locals}) in a colon definition:
 1873: 
 1874: @example
 1875: : swap @{ a b -- b a @}
 1876:   b a ;
 1877: 1 2 swap .s 2drop
 1878: @end example
 1879: 
 1880: (If your Forth system does not support this syntax, include
 1881: @file{compat/anslocal.fs} first).
 1882: 
 1883: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1884: takes two cells from the stack, puts the top of stack in @code{b} and
 1885: the next stack element in @code{a}.  @code{--} starts a comment ending
 1886: with @code{@}}.  After the locals definition, using the name of the
 1887: local will push its value on the stack.  You can leave the comment
 1888: part (@code{-- b a}) away:
 1889: 
 1890: @example
 1891: : swap ( x1 x2 -- x2 x1 )
 1892:   @{ a b @} b a ;
 1893: @end example
 1894: 
 1895: In Gforth you can have several locals definitions, anywhere in a colon
 1896: definition; in contrast, in a standard program you can have only one
 1897: locals definition per colon definition, and that locals definition must
 1898: be outside any control structure.
 1899: 
 1900: With locals you can write slightly longer definitions without running
 1901: into stack trouble.  However, I recommend trying to write colon
 1902: definitions without locals for exercise purposes to help you gain the
 1903: essential factoring skills.
 1904: 
 1905: @quotation Assignment
 1906: Rewrite your definitions until now with locals
 1907: @end quotation
 1908: 
 1909: Reference: @ref{Locals}.
 1910: 
 1911: 
 1912: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1913: @section Conditional execution
 1914: @cindex conditionals, tutorial
 1915: @cindex if, tutorial
 1916: 
 1917: In Forth you can use control structures only inside colon definitions.
 1918: An @code{if}-structure looks like this:
 1919: 
 1920: @example
 1921: : abs ( n1 -- +n2 )
 1922:     dup 0 < if
 1923:         negate
 1924:     endif ;
 1925: 5 abs .
 1926: -5 abs .
 1927: @end example
 1928: 
 1929: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1930: the following code is performed, otherwise execution continues after the
 1931: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1932: elements and produces a flag:
 1933: 
 1934: @example
 1935: 1 2 < .
 1936: 2 1 < .
 1937: 1 1 < .
 1938: @end example
 1939: 
 1940: Actually the standard name for @code{endif} is @code{then}.  This
 1941: tutorial presents the examples using @code{endif}, because this is often
 1942: less confusing for people familiar with other programming languages
 1943: where @code{then} has a different meaning.  If your system does not have
 1944: @code{endif}, define it with
 1945: 
 1946: @example
 1947: : endif postpone then ; immediate
 1948: @end example
 1949: 
 1950: You can optionally use an @code{else}-part:
 1951: 
 1952: @example
 1953: : min ( n1 n2 -- n )
 1954:   2dup < if
 1955:     drop
 1956:   else
 1957:     nip
 1958:   endif ;
 1959: 2 3 min .
 1960: 3 2 min .
 1961: @end example
 1962: 
 1963: @quotation Assignment
 1964: Write @code{min} without @code{else}-part (hint: what's the definition
 1965: of @code{nip}?).
 1966: @end quotation
 1967: 
 1968: Reference: @ref{Selection}.
 1969: 
 1970: 
 1971: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1972: @section Flags and Comparisons
 1973: @cindex flags tutorial
 1974: @cindex comparison tutorial
 1975: 
 1976: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1977: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1978: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1979: treated as true flag.
 1980: 
 1981: @example
 1982: false .
 1983: true .
 1984: true hex u. decimal
 1985: @end example
 1986: 
 1987: Comparison words produce canonical flags:
 1988: 
 1989: @example
 1990: 1 1 = .
 1991: 1 0= .
 1992: 0 1 < .
 1993: 0 0 < .
 1994: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1995: -1 1 < .
 1996: @end example
 1997: 
 1998: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1999: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 2000: these combinations are standard (for details see the standard,
 2001: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 2002: 
 2003: You can use @code{and or xor invert} as operations on canonical flags.
 2004: Actually they are bitwise operations:
 2005: 
 2006: @example
 2007: 1 2 and .
 2008: 1 2 or .
 2009: 1 3 xor .
 2010: 1 invert .
 2011: @end example
 2012: 
 2013: You can convert a zero/non-zero flag into a canonical flag with
 2014: @code{0<>} (and complement it on the way with @code{0=}).
 2015: 
 2016: @example
 2017: 1 0= .
 2018: 1 0<> .
 2019: @end example
 2020: 
 2021: You can use the all-bits-set feature of canonical flags and the bitwise
 2022: operation of the Boolean operations to avoid @code{if}s:
 2023: 
 2024: @example
 2025: : foo ( n1 -- n2 )
 2026:   0= if
 2027:     14
 2028:   else
 2029:     0
 2030:   endif ;
 2031: 0 foo .
 2032: 1 foo .
 2033: 
 2034: : foo ( n1 -- n2 )
 2035:   0= 14 and ;
 2036: 0 foo .
 2037: 1 foo .
 2038: @end example
 2039: 
 2040: @quotation Assignment
 2041: Write @code{min} without @code{if}.
 2042: @end quotation
 2043: 
 2044: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2045: @ref{Bitwise operations}.
 2046: 
 2047: 
 2048: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2049: @section General Loops
 2050: @cindex loops, indefinite, tutorial
 2051: 
 2052: The endless loop is the most simple one:
 2053: 
 2054: @example
 2055: : endless ( -- )
 2056:   0 begin
 2057:     dup . 1+
 2058:   again ;
 2059: endless
 2060: @end example
 2061: 
 2062: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2063: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2064: 
 2065: A loop with one exit at any place looks like this:
 2066: 
 2067: @example
 2068: : log2 ( +n1 -- n2 )
 2069: \ logarithmus dualis of n1>0, rounded down to the next integer
 2070:   assert( dup 0> )
 2071:   2/ 0 begin
 2072:     over 0> while
 2073:       1+ swap 2/ swap
 2074:   repeat
 2075:   nip ;
 2076: 7 log2 .
 2077: 8 log2 .
 2078: @end example
 2079: 
 2080: At run-time @code{while} consumes a flag; if it is 0, execution
 2081: continues behind the @code{repeat}; if the flag is non-zero, execution
 2082: continues behind the @code{while}.  @code{Repeat} jumps back to
 2083: @code{begin}, just like @code{again}.
 2084: 
 2085: In Forth there are a number of combinations/abbreviations, like
 2086: @code{1+}.  However, @code{2/} is not one of them; it shifts its
 2087: argument right by one bit (arithmetic shift right), and viewed as
 2088: division that always rounds towards negative infinity (floored
 2089: division).  In contrast, @code{/} rounds towards zero on some systems
 2090: (not on default installations of gforth (>=0.7.0), however).
 2091: 
 2092: @example
 2093: -5 2 / . \ -2 or -3
 2094: -5 2/ .  \ -3
 2095: @end example
 2096: 
 2097: @code{assert(} is no standard word, but you can get it on systems other
 2098: than Gforth by including @file{compat/assert.fs}.  You can see what it
 2099: does by trying
 2100: 
 2101: @example
 2102: 0 log2 .
 2103: @end example
 2104: 
 2105: Here's a loop with an exit at the end:
 2106: 
 2107: @example
 2108: : log2 ( +n1 -- n2 )
 2109: \ logarithmus dualis of n1>0, rounded down to the next integer
 2110:   assert( dup 0 > )
 2111:   -1 begin
 2112:     1+ swap 2/ swap
 2113:     over 0 <=
 2114:   until
 2115:   nip ;
 2116: @end example
 2117: 
 2118: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2119: the @code{begin}, otherwise after the @code{until}.
 2120: 
 2121: @quotation Assignment
 2122: Write a definition for computing the greatest common divisor.
 2123: @end quotation
 2124: 
 2125: Reference: @ref{Simple Loops}.
 2126: 
 2127: 
 2128: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2129: @section Counted loops
 2130: @cindex loops, counted, tutorial
 2131: 
 2132: @example
 2133: : ^ ( n1 u -- n )
 2134: \ n = the uth power of n1
 2135:   1 swap 0 u+do
 2136:     over *
 2137:   loop
 2138:   nip ;
 2139: 3 2 ^ .
 2140: 4 3 ^ .
 2141: @end example
 2142: 
 2143: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2144: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2145: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2146: times (or not at all, if @code{u3-u4<0}).
 2147: 
 2148: You can see the stack effect design rules at work in the stack effect of
 2149: the loop start words: Since the start value of the loop is more
 2150: frequently constant than the end value, the start value is passed on
 2151: the top-of-stack.
 2152: 
 2153: You can access the counter of a counted loop with @code{i}:
 2154: 
 2155: @example
 2156: : fac ( u -- u! )
 2157:   1 swap 1+ 1 u+do
 2158:     i *
 2159:   loop ;
 2160: 5 fac .
 2161: 7 fac .
 2162: @end example
 2163: 
 2164: There is also @code{+do}, which expects signed numbers (important for
 2165: deciding whether to enter the loop).
 2166: 
 2167: @quotation Assignment
 2168: Write a definition for computing the nth Fibonacci number.
 2169: @end quotation
 2170: 
 2171: You can also use increments other than 1:
 2172: 
 2173: @example
 2174: : up2 ( n1 n2 -- )
 2175:   +do
 2176:     i .
 2177:   2 +loop ;
 2178: 10 0 up2
 2179: 
 2180: : down2 ( n1 n2 -- )
 2181:   -do
 2182:     i .
 2183:   2 -loop ;
 2184: 0 10 down2
 2185: @end example
 2186: 
 2187: Reference: @ref{Counted Loops}.
 2188: 
 2189: 
 2190: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2191: @section Recursion
 2192: @cindex recursion tutorial
 2193: 
 2194: Usually the name of a definition is not visible in the definition; but
 2195: earlier definitions are usually visible:
 2196: 
 2197: @example
 2198: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
 2199: : / ( n1 n2 -- n )
 2200:   dup 0= if
 2201:     -10 throw \ report division by zero
 2202:   endif
 2203:   /           \ old version
 2204: ;
 2205: 1 0 /
 2206: @end example
 2207: 
 2208: For recursive definitions you can use @code{recursive} (non-standard) or
 2209: @code{recurse}:
 2210: 
 2211: @example
 2212: : fac1 ( n -- n! ) recursive
 2213:  dup 0> if
 2214:    dup 1- fac1 *
 2215:  else
 2216:    drop 1
 2217:  endif ;
 2218: 7 fac1 .
 2219: 
 2220: : fac2 ( n -- n! )
 2221:  dup 0> if
 2222:    dup 1- recurse *
 2223:  else
 2224:    drop 1
 2225:  endif ;
 2226: 8 fac2 .
 2227: @end example
 2228: 
 2229: @quotation Assignment
 2230: Write a recursive definition for computing the nth Fibonacci number.
 2231: @end quotation
 2232: 
 2233: Reference (including indirect recursion): @xref{Calls and returns}.
 2234: 
 2235: 
 2236: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2237: @section Leaving definitions or loops
 2238: @cindex leaving definitions, tutorial
 2239: @cindex leaving loops, tutorial
 2240: 
 2241: @code{EXIT} exits the current definition right away.  For every counted
 2242: loop that is left in this way, an @code{UNLOOP} has to be performed
 2243: before the @code{EXIT}:
 2244: 
 2245: @c !! real examples
 2246: @example
 2247: : ...
 2248:  ... u+do
 2249:    ... if
 2250:      ... unloop exit
 2251:    endif
 2252:    ...
 2253:  loop
 2254:  ... ;
 2255: @end example
 2256: 
 2257: @code{LEAVE} leaves the innermost counted loop right away:
 2258: 
 2259: @example
 2260: : ...
 2261:  ... u+do
 2262:    ... if
 2263:      ... leave
 2264:    endif
 2265:    ...
 2266:  loop
 2267:  ... ;
 2268: @end example
 2269: 
 2270: @c !! example
 2271: 
 2272: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2273: 
 2274: 
 2275: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2276: @section Return Stack
 2277: @cindex return stack tutorial
 2278: 
 2279: In addition to the data stack Forth also has a second stack, the return
 2280: stack; most Forth systems store the return addresses of procedure calls
 2281: there (thus its name).  Programmers can also use this stack:
 2282: 
 2283: @example
 2284: : foo ( n1 n2 -- )
 2285:  .s
 2286:  >r .s
 2287:  r@@ .
 2288:  >r .s
 2289:  r@@ .
 2290:  r> .
 2291:  r@@ .
 2292:  r> . ;
 2293: 1 2 foo
 2294: @end example
 2295: 
 2296: @code{>r} takes an element from the data stack and pushes it onto the
 2297: return stack; conversely, @code{r>} moves an elementm from the return to
 2298: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2299: on the data stack.
 2300: 
 2301: Forth programmers usually use the return stack for storing data
 2302: temporarily, if using the data stack alone would be too complex, and
 2303: factoring and locals are not an option:
 2304: 
 2305: @example
 2306: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2307:  rot >r rot r> ;
 2308: @end example
 2309: 
 2310: The return address of the definition and the loop control parameters of
 2311: counted loops usually reside on the return stack, so you have to take
 2312: all items, that you have pushed on the return stack in a colon
 2313: definition or counted loop, from the return stack before the definition
 2314: or loop ends.  You cannot access items that you pushed on the return
 2315: stack outside some definition or loop within the definition of loop.
 2316: 
 2317: If you miscount the return stack items, this usually ends in a crash:
 2318: 
 2319: @example
 2320: : crash ( n -- )
 2321:   >r ;
 2322: 5 crash
 2323: @end example
 2324: 
 2325: You cannot mix using locals and using the return stack (according to the
 2326: standard; Gforth has no problem).  However, they solve the same
 2327: problems, so this shouldn't be an issue.
 2328: 
 2329: @quotation Assignment
 2330: Can you rewrite any of the definitions you wrote until now in a better
 2331: way using the return stack?
 2332: @end quotation
 2333: 
 2334: Reference: @ref{Return stack}.
 2335: 
 2336: 
 2337: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2338: @section Memory
 2339: @cindex memory access/allocation tutorial
 2340: 
 2341: You can create a global variable @code{v} with
 2342: 
 2343: @example
 2344: variable v ( -- addr )
 2345: @end example
 2346: 
 2347: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2348: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2349: values into this cell and @code{@@} (fetch) to load the value from the
 2350: stack into memory:
 2351: 
 2352: @example
 2353: v .
 2354: 5 v ! .s
 2355: v @@ .
 2356: @end example
 2357: 
 2358: You can see a raw dump of memory with @code{dump}:
 2359: 
 2360: @example
 2361: v 1 cells .s dump
 2362: @end example
 2363: 
 2364: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2365: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2366: also reserve more memory:
 2367: 
 2368: @example
 2369: create v2 20 cells allot
 2370: v2 20 cells dump
 2371: @end example
 2372: 
 2373: creates a variable-like word @code{v2} and reserves 20 uninitialized
 2374: cells; the address pushed by @code{v2} points to the start of these 20
 2375: cells (@pxref{CREATE}).  You can use address arithmetic to access
 2376: these cells:
 2377: 
 2378: @example
 2379: 3 v2 5 cells + !
 2380: v2 20 cells dump
 2381: @end example
 2382: 
 2383: You can reserve and initialize memory with @code{,}:
 2384: 
 2385: @example
 2386: create v3
 2387:   5 , 4 , 3 , 2 , 1 ,
 2388: v3 @@ .
 2389: v3 cell+ @@ .
 2390: v3 2 cells + @@ .
 2391: v3 5 cells dump
 2392: @end example
 2393: 
 2394: @quotation Assignment
 2395: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2396: @code{u} cells, with the first of these cells at @code{addr}, the next
 2397: one at @code{addr cell+} etc.
 2398: @end quotation
 2399: 
 2400: The difference between @code{variable} and @code{create} is that
 2401: @code{variable} allots a cell, and that you cannot allot additional
 2402: memory to a variable in standard Forth.
 2403: 
 2404: You can also reserve memory without creating a new word:
 2405: 
 2406: @example
 2407: here 10 cells allot .
 2408: here .
 2409: @end example
 2410: 
 2411: The first @code{here} pushes the start address of the memory area, the
 2412: second @code{here} the address after the dictionary area.  You should
 2413: store the start address somewhere, or you will have a hard time
 2414: finding the memory area again.
 2415: 
 2416: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2417: the system's data structures for words etc. on Gforth and most other
 2418: Forth systems.  It is managed like a stack: You can free the memory that
 2419: you have just @code{allot}ed with
 2420: 
 2421: @example
 2422: -10 cells allot
 2423: here .
 2424: @end example
 2425: 
 2426: Note that you cannot do this if you have created a new word in the
 2427: meantime (because then your @code{allot}ed memory is no longer on the
 2428: top of the dictionary ``stack'').
 2429: 
 2430: Alternatively, you can use @code{allocate} and @code{free} which allow
 2431: freeing memory in any order:
 2432: 
 2433: @example
 2434: 10 cells allocate throw .s
 2435: 20 cells allocate throw .s
 2436: swap
 2437: free throw
 2438: free throw
 2439: @end example
 2440: 
 2441: The @code{throw}s deal with errors (e.g., out of memory).
 2442: 
 2443: And there is also a
 2444: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2445: garbage collector}, which eliminates the need to @code{free} memory
 2446: explicitly.
 2447: 
 2448: Reference: @ref{Memory}.
 2449: 
 2450: 
 2451: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2452: @section Characters and Strings
 2453: @cindex strings tutorial
 2454: @cindex characters tutorial
 2455: 
 2456: On the stack characters take up a cell, like numbers.  In memory they
 2457: have their own size (one 8-bit byte on most systems), and therefore
 2458: require their own words for memory access:
 2459: 
 2460: @example
 2461: create v4 
 2462:   104 c, 97 c, 108 c, 108 c, 111 c,
 2463: v4 4 chars + c@@ .
 2464: v4 5 chars dump
 2465: @end example
 2466: 
 2467: The preferred representation of strings on the stack is @code{addr
 2468: u-count}, where @code{addr} is the address of the first character and
 2469: @code{u-count} is the number of characters in the string.
 2470: 
 2471: @example
 2472: v4 5 type
 2473: @end example
 2474: 
 2475: You get a string constant with
 2476: 
 2477: @example
 2478: s" hello, world" .s
 2479: type
 2480: @end example
 2481: 
 2482: Make sure you have a space between @code{s"} and the string; @code{s"}
 2483: is a normal Forth word and must be delimited with white space (try what
 2484: happens when you remove the space).
 2485: 
 2486: However, this interpretive use of @code{s"} is quite restricted: the
 2487: string exists only until the next call of @code{s"} (some Forth systems
 2488: keep more than one of these strings, but usually they still have a
 2489: limited lifetime).
 2490: 
 2491: @example
 2492: s" hello," s" world" .s
 2493: type
 2494: type
 2495: @end example
 2496: 
 2497: You can also use @code{s"} in a definition, and the resulting
 2498: strings then live forever (well, for as long as the definition):
 2499: 
 2500: @example
 2501: : foo s" hello," s" world" ;
 2502: foo .s
 2503: type
 2504: type
 2505: @end example
 2506: 
 2507: @quotation Assignment
 2508: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2509: Implement @code{type ( addr u -- )}.
 2510: @end quotation
 2511: 
 2512: Reference: @ref{Memory Blocks}.
 2513: 
 2514: 
 2515: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
 2516: @section Alignment
 2517: @cindex alignment tutorial
 2518: @cindex memory alignment tutorial
 2519: 
 2520: On many processors cells have to be aligned in memory, if you want to
 2521: access them with @code{@@} and @code{!} (and even if the processor does
 2522: not require alignment, access to aligned cells is faster).
 2523: 
 2524: @code{Create} aligns @code{here} (i.e., the place where the next
 2525: allocation will occur, and that the @code{create}d word points to).
 2526: Likewise, the memory produced by @code{allocate} starts at an aligned
 2527: address.  Adding a number of @code{cells} to an aligned address produces
 2528: another aligned address.
 2529: 
 2530: However, address arithmetic involving @code{char+} and @code{chars} can
 2531: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2532: a-addr )} produces the next aligned address:
 2533: 
 2534: @example
 2535: v3 char+ aligned .s @@ .
 2536: v3 char+ .s @@ .
 2537: @end example
 2538: 
 2539: Similarly, @code{align} advances @code{here} to the next aligned
 2540: address:
 2541: 
 2542: @example
 2543: create v5 97 c,
 2544: here .
 2545: align here .
 2546: 1000 ,
 2547: @end example
 2548: 
 2549: Note that you should use aligned addresses even if your processor does
 2550: not require them, if you want your program to be portable.
 2551: 
 2552: Reference: @ref{Address arithmetic}.
 2553: 
 2554: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
 2555: @section Floating Point
 2556: @cindex floating point tutorial
 2557: @cindex FP tutorial
 2558: 
 2559: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
 2560: might expect, but there are a few things worth noting:
 2561: 
 2562: The first point is not specific to Forth, but so important and yet not
 2563: universally known that I mention it here: FP numbers are not reals.
 2564: Many properties (e.g., arithmetic laws) that reals have and that one
 2565: expects of all kinds of numbers do not hold for FP numbers.  If you
 2566: want to use FP computations, you should learn about their problems and
 2567: how to avoid them; a good starting point is @cite{David Goldberg,
 2568: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 2569: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 2570: Computing Surveys 23(1):5@minus{}48, March 1991}.
 2571: 
 2572: In Forth source code literal FP numbers need an exponent, e.g.,
 2573: @code{1e0}; this can also be written shorter as @code{1e}, longer as
 2574: @code{+1.0e+0}, and many variations in between.  The reason for this is
 2575: that, for historical reasons, Forth interprets a decimal point alone
 2576: (e.g., @code{1.}) as indicating a double-cell integer.  Examples:
 2577: 
 2578: @example
 2579: 2e 2e f+ f.
 2580: @end example
 2581: 
 2582: Another requirement for literal FP numbers is that the current base is
 2583: decimal; with a hex base @code{1e} is interpreted as an integer.
 2584: 
 2585: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
 2586: ANS Forth system may implement the FP stack on the data stack, but
 2587: virtually all systems implement a separate FP stack; and programming
 2588: in a way that accommodates all models is so cumbersome that nobody
 2589: does it.}  One advantage of this model is that cells are not in the
 2590: way when accessing FP values, and vice versa.  Forth has a set of
 2591: words for manipulating the FP stack: @code{fdup fswap fdrop fover
 2592: frot} and (non-standard) @code{fnip ftuck fpick}.
 2593: 
 2594: FP arithmetic words are prefixed with @code{F}.  There is the usual
 2595: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
 2596: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
 2597: might expect is @code{f=}; but @code{f=} is non-standard, because FP
 2598: computation results are usually inaccurate, so exact comparison is
 2599: usually a mistake, and one should use approximate comparison.
 2600: Unfortunately, @code{f~}, the standard word for that purpose, is not
 2601: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
 2602: well.
 2603: 
 2604: And of course there are words for accessing FP numbers in memory
 2605: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
 2606: faligned}).  There are also variants of these words with an @code{sf}
 2607: and @code{df} prefix for accessing IEEE format single-precision and
 2608: double-precision numbers in memory; their main purpose is for
 2609: accessing external FP data (e.g., that has been read from or will be
 2610: written to a file).
 2611: 
 2612: Here is an example of a dot-product word and its use:
 2613: 
 2614: @example
 2615: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 2616:   >r swap 2swap swap 0e r> 0 ?DO
 2617:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 2618:   LOOP
 2619:   2drop 2drop ;
 2620: 
 2621: create v 1.23e f, 4.56e f, 7.89e f,
 2622: 
 2623: v 1 floats  v 1 floats  3  v* f.
 2624: @end example
 2625: 
 2626: @quotation Assignment
 2627: Write a program to solve a quadratic equation.  Then read @cite{Henry
 2628: G. Baker,
 2629: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
 2630: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
 2631: 33(1):30@minus{}39, January 1998}, and see if you can improve your
 2632: program.  Finally, find a test case where the original and the
 2633: improved version produce different results.
 2634: @end quotation
 2635: 
 2636: Reference: @ref{Floating Point}; @ref{Floating point stack};
 2637: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
 2638: arithmetic}.
 2639: 
 2640: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
 2641: @section Files
 2642: @cindex files tutorial
 2643: 
 2644: This section gives a short introduction into how to use files inside
 2645: Forth. It's broken up into five easy steps:
 2646: 
 2647: @enumerate 1
 2648: @item Opened an ASCII text file for input
 2649: @item Opened a file for output
 2650: @item Read input file until string matched (or some other condition matched)
 2651: @item Wrote some lines from input ( modified or not) to output
 2652: @item Closed the files.
 2653: @end enumerate
 2654: 
 2655: Reference: @ref{General files}.
 2656: 
 2657: @subsection Open file for input
 2658: 
 2659: @example
 2660: s" foo.in"  r/o open-file throw Value fd-in
 2661: @end example
 2662: 
 2663: @subsection Create file for output
 2664: 
 2665: @example
 2666: s" foo.out" w/o create-file throw Value fd-out
 2667: @end example
 2668: 
 2669: The available file modes are r/o for read-only access, r/w for
 2670: read-write access, and w/o for write-only access. You could open both
 2671: files with r/w, too, if you like. All file words return error codes; for
 2672: most applications, it's best to pass there error codes with @code{throw}
 2673: to the outer error handler.
 2674: 
 2675: If you want words for opening and assigning, define them as follows:
 2676: 
 2677: @example
 2678: 0 Value fd-in
 2679: 0 Value fd-out
 2680: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2681: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2682: @end example
 2683: 
 2684: Usage example:
 2685: 
 2686: @example
 2687: s" foo.in" open-input
 2688: s" foo.out" open-output
 2689: @end example
 2690: 
 2691: @subsection Scan file for a particular line
 2692: 
 2693: @example
 2694: 256 Constant max-line
 2695: Create line-buffer  max-line 2 + allot
 2696: 
 2697: : scan-file ( addr u -- )
 2698:   begin
 2699:       line-buffer max-line fd-in read-line throw
 2700:   while
 2701:          >r 2dup line-buffer r> compare 0=
 2702:      until
 2703:   else
 2704:      drop
 2705:   then
 2706:   2drop ;
 2707: @end example
 2708: 
 2709: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2710: the buffer at addr, and returns the number of bytes read, a flag that is
 2711: false when the end of file is reached, and an error code.
 2712: 
 2713: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2714: returns zero if both strings are equal. It returns a positive number if
 2715: the first string is lexically greater, a negative if the second string
 2716: is lexically greater.
 2717: 
 2718: We haven't seen this loop here; it has two exits. Since the @code{while}
 2719: exits with the number of bytes read on the stack, we have to clean up
 2720: that separately; that's after the @code{else}.
 2721: 
 2722: Usage example:
 2723: 
 2724: @example
 2725: s" The text I search is here" scan-file
 2726: @end example
 2727: 
 2728: @subsection Copy input to output
 2729: 
 2730: @example
 2731: : copy-file ( -- )
 2732:   begin
 2733:       line-buffer max-line fd-in read-line throw
 2734:   while
 2735:       line-buffer swap fd-out write-line throw
 2736:   repeat 
 2737:   drop ;
 2738: @end example
 2739: @c !! does not handle long lines, no newline at end of file
 2740: 
 2741: @subsection Close files
 2742: 
 2743: @example
 2744: fd-in close-file throw
 2745: fd-out close-file throw
 2746: @end example
 2747: 
 2748: Likewise, you can put that into definitions, too:
 2749: 
 2750: @example
 2751: : close-input ( -- )  fd-in close-file throw ;
 2752: : close-output ( -- )  fd-out close-file throw ;
 2753: @end example
 2754: 
 2755: @quotation Assignment
 2756: How could you modify @code{copy-file} so that it copies until a second line is
 2757: matched? Can you write a program that extracts a section of a text file,
 2758: given the line that starts and the line that terminates that section?
 2759: @end quotation
 2760: 
 2761: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2762: @section Interpretation and Compilation Semantics and Immediacy
 2763: @cindex semantics tutorial
 2764: @cindex interpretation semantics tutorial
 2765: @cindex compilation semantics tutorial
 2766: @cindex immediate, tutorial
 2767: 
 2768: When a word is compiled, it behaves differently from being interpreted.
 2769: E.g., consider @code{+}:
 2770: 
 2771: @example
 2772: 1 2 + .
 2773: : foo + ;
 2774: @end example
 2775: 
 2776: These two behaviours are known as compilation and interpretation
 2777: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2778: is to append the interpretation semantics to the currently defined word
 2779: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2780: later, the interpretation semantics of @code{+} (i.e., adding two
 2781: numbers) will be performed.
 2782: 
 2783: However, there are words with non-default compilation semantics, e.g.,
 2784: the control-flow words like @code{if}.  You can use @code{immediate} to
 2785: change the compilation semantics of the last defined word to be equal to
 2786: the interpretation semantics:
 2787: 
 2788: @example
 2789: : [FOO] ( -- )
 2790:  5 . ; immediate
 2791: 
 2792: [FOO]
 2793: : bar ( -- )
 2794:   [FOO] ;
 2795: bar
 2796: see bar
 2797: @end example
 2798: 
 2799: Two conventions to mark words with non-default compilation semantics are
 2800: names with brackets (more frequently used) and to write them all in
 2801: upper case (less frequently used).
 2802: 
 2803: In Gforth (and many other systems) you can also remove the
 2804: interpretation semantics with @code{compile-only} (the compilation
 2805: semantics is derived from the original interpretation semantics):
 2806: 
 2807: @example
 2808: : flip ( -- )
 2809:  6 . ; compile-only \ but not immediate
 2810: flip
 2811: 
 2812: : flop ( -- )
 2813:  flip ;
 2814: flop
 2815: @end example
 2816: 
 2817: In this example the interpretation semantics of @code{flop} is equal to
 2818: the original interpretation semantics of @code{flip}.
 2819: 
 2820: The text interpreter has two states: in interpret state, it performs the
 2821: interpretation semantics of words it encounters; in compile state, it
 2822: performs the compilation semantics of these words.
 2823: 
 2824: Among other things, @code{:} switches into compile state, and @code{;}
 2825: switches back to interpret state.  They contain the factors @code{]}
 2826: (switch to compile state) and @code{[} (switch to interpret state), that
 2827: do nothing but switch the state.
 2828: 
 2829: @example
 2830: : xxx ( -- )
 2831:   [ 5 . ]
 2832: ;
 2833: 
 2834: xxx
 2835: see xxx
 2836: @end example
 2837: 
 2838: These brackets are also the source of the naming convention mentioned
 2839: above.
 2840: 
 2841: Reference: @ref{Interpretation and Compilation Semantics}.
 2842: 
 2843: 
 2844: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2845: @section Execution Tokens
 2846: @cindex execution tokens tutorial
 2847: @cindex XT tutorial
 2848: 
 2849: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2850: cell representing the interpretation semantics of a word.  You can
 2851: execute this semantics with @code{execute}:
 2852: 
 2853: @example
 2854: ' + .s
 2855: 1 2 rot execute .
 2856: @end example
 2857: 
 2858: The XT is similar to a function pointer in C.  However, parameter
 2859: passing through the stack makes it a little more flexible:
 2860: 
 2861: @example
 2862: : map-array ( ... addr u xt -- ... )
 2863: \ executes xt ( ... x -- ... ) for every element of the array starting
 2864: \ at addr and containing u elements
 2865:   @{ xt @}
 2866:   cells over + swap ?do
 2867:     i @@ xt execute
 2868:   1 cells +loop ;
 2869: 
 2870: create a 3 , 4 , 2 , -1 , 4 ,
 2871: a 5 ' . map-array .s
 2872: 0 a 5 ' + map-array .
 2873: s" max-n" environment? drop .s
 2874: a 5 ' min map-array .
 2875: @end example
 2876: 
 2877: You can use map-array with the XTs of words that consume one element
 2878: more than they produce.  In theory you can also use it with other XTs,
 2879: but the stack effect then depends on the size of the array, which is
 2880: hard to understand.
 2881: 
 2882: Since XTs are cell-sized, you can store them in memory and manipulate
 2883: them on the stack like other cells.  You can also compile the XT into a
 2884: word with @code{compile,}:
 2885: 
 2886: @example
 2887: : foo1 ( n1 n2 -- n )
 2888:    [ ' + compile, ] ;
 2889: see foo1
 2890: @end example
 2891: 
 2892: This is non-standard, because @code{compile,} has no compilation
 2893: semantics in the standard, but it works in good Forth systems.  For the
 2894: broken ones, use
 2895: 
 2896: @example
 2897: : [compile,] compile, ; immediate
 2898: 
 2899: : foo1 ( n1 n2 -- n )
 2900:    [ ' + ] [compile,] ;
 2901: see foo
 2902: @end example
 2903: 
 2904: @code{'} is a word with default compilation semantics; it parses the
 2905: next word when its interpretation semantics are executed, not during
 2906: compilation:
 2907: 
 2908: @example
 2909: : foo ( -- xt )
 2910:   ' ;
 2911: see foo
 2912: : bar ( ... "word" -- ... )
 2913:   ' execute ;
 2914: see bar
 2915: 1 2 bar + .
 2916: @end example
 2917: 
 2918: You often want to parse a word during compilation and compile its XT so
 2919: it will be pushed on the stack at run-time.  @code{[']} does this:
 2920: 
 2921: @example
 2922: : xt-+ ( -- xt )
 2923:   ['] + ;
 2924: see xt-+
 2925: 1 2 xt-+ execute .
 2926: @end example
 2927: 
 2928: Many programmers tend to see @code{'} and the word it parses as one
 2929: unit, and expect it to behave like @code{[']} when compiled, and are
 2930: confused by the actual behaviour.  If you are, just remember that the
 2931: Forth system just takes @code{'} as one unit and has no idea that it is
 2932: a parsing word (attempts to convenience programmers in this issue have
 2933: usually resulted in even worse pitfalls, see
 2934: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2935: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2936: 
 2937: Note that the state of the interpreter does not come into play when
 2938: creating and executing XTs.  I.e., even when you execute @code{'} in
 2939: compile state, it still gives you the interpretation semantics.  And
 2940: whatever that state is, @code{execute} performs the semantics
 2941: represented by the XT (i.e., for XTs produced with @code{'} the
 2942: interpretation semantics).
 2943: 
 2944: Reference: @ref{Tokens for Words}.
 2945: 
 2946: 
 2947: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2948: @section Exceptions
 2949: @cindex exceptions tutorial
 2950: 
 2951: @code{throw ( n -- )} causes an exception unless n is zero.
 2952: 
 2953: @example
 2954: 100 throw .s
 2955: 0 throw .s
 2956: @end example
 2957: 
 2958: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2959: it catches exceptions and pushes the number of the exception on the
 2960: stack (or 0, if the xt executed without exception).  If there was an
 2961: exception, the stacks have the same depth as when entering @code{catch}:
 2962: 
 2963: @example
 2964: .s
 2965: 3 0 ' / catch .s
 2966: 3 2 ' / catch .s
 2967: @end example
 2968: 
 2969: @quotation Assignment
 2970: Try the same with @code{execute} instead of @code{catch}.
 2971: @end quotation
 2972: 
 2973: @code{Throw} always jumps to the dynamically next enclosing
 2974: @code{catch}, even if it has to leave several call levels to achieve
 2975: this:
 2976: 
 2977: @example
 2978: : foo 100 throw ;
 2979: : foo1 foo ." after foo" ;
 2980: : bar ['] foo1 catch ;
 2981: bar .
 2982: @end example
 2983: 
 2984: It is often important to restore a value upon leaving a definition, even
 2985: if the definition is left through an exception.  You can ensure this
 2986: like this:
 2987: 
 2988: @example
 2989: : ...
 2990:    save-x
 2991:    ['] word-changing-x catch ( ... n )
 2992:    restore-x
 2993:    ( ... n ) throw ;
 2994: @end example
 2995: 
 2996: However, this is still not safe against, e.g., the user pressing
 2997: @kbd{Ctrl-C} when execution is between the @code{catch} and
 2998: @code{restore-x}.
 2999: 
 3000: Gforth provides an alternative exception handling syntax that is safe
 3001: against such cases: @code{try ... restore ... endtry}.  If the code
 3002: between @code{try} and @code{endtry} has an exception, the stack
 3003: depths are restored, the exception number is pushed on the stack, and
 3004: the execution continues right after @code{restore}.
 3005: 
 3006: The safer equivalent to the restoration code above is
 3007: 
 3008: @example
 3009: : ...
 3010:   save-x
 3011:   try
 3012:     word-changing-x 0
 3013:   restore
 3014:     restore-x
 3015:   endtry
 3016:   throw ;
 3017: @end example
 3018: 
 3019: Reference: @ref{Exception Handling}.
 3020: 
 3021: 
 3022: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 3023: @section Defining Words
 3024: @cindex defining words tutorial
 3025: @cindex does> tutorial
 3026: @cindex create...does> tutorial
 3027: 
 3028: @c before semantics?
 3029: 
 3030: @code{:}, @code{create}, and @code{variable} are definition words: They
 3031: define other words.  @code{Constant} is another definition word:
 3032: 
 3033: @example
 3034: 5 constant foo
 3035: foo .
 3036: @end example
 3037: 
 3038: You can also use the prefixes @code{2} (double-cell) and @code{f}
 3039: (floating point) with @code{variable} and @code{constant}.
 3040: 
 3041: You can also define your own defining words.  E.g.:
 3042: 
 3043: @example
 3044: : variable ( "name" -- )
 3045:   create 0 , ;
 3046: @end example
 3047: 
 3048: You can also define defining words that create words that do something
 3049: other than just producing their address:
 3050: 
 3051: @example
 3052: : constant ( n "name" -- )
 3053:   create ,
 3054: does> ( -- n )
 3055:   ( addr ) @@ ;
 3056: 
 3057: 5 constant foo
 3058: foo .
 3059: @end example
 3060: 
 3061: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 3062: @code{does>} replaces @code{;}, but it also does something else: It
 3063: changes the last defined word such that it pushes the address of the
 3064: body of the word and then performs the code after the @code{does>}
 3065: whenever it is called.
 3066: 
 3067: In the example above, @code{constant} uses @code{,} to store 5 into the
 3068: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 3069: the body onto the stack, then (in the code after the @code{does>})
 3070: fetches the 5 from there.
 3071: 
 3072: The stack comment near the @code{does>} reflects the stack effect of the
 3073: defined word, not the stack effect of the code after the @code{does>}
 3074: (the difference is that the code expects the address of the body that
 3075: the stack comment does not show).
 3076: 
 3077: You can use these definition words to do factoring in cases that involve
 3078: (other) definition words.  E.g., a field offset is always added to an
 3079: address.  Instead of defining
 3080: 
 3081: @example
 3082: 2 cells constant offset-field1
 3083: @end example
 3084: 
 3085: and using this like
 3086: 
 3087: @example
 3088: ( addr ) offset-field1 +
 3089: @end example
 3090: 
 3091: you can define a definition word
 3092: 
 3093: @example
 3094: : simple-field ( n "name" -- )
 3095:   create ,
 3096: does> ( n1 -- n1+n )
 3097:   ( addr ) @@ + ;
 3098: @end example
 3099: 
 3100: Definition and use of field offsets now look like this:
 3101: 
 3102: @example
 3103: 2 cells simple-field field1
 3104: create mystruct 4 cells allot
 3105: mystruct .s field1 .s drop
 3106: @end example
 3107: 
 3108: If you want to do something with the word without performing the code
 3109: after the @code{does>}, you can access the body of a @code{create}d word
 3110: with @code{>body ( xt -- addr )}:
 3111: 
 3112: @example
 3113: : value ( n "name" -- )
 3114:   create ,
 3115: does> ( -- n1 )
 3116:   @@ ;
 3117: : to ( n "name" -- )
 3118:   ' >body ! ;
 3119: 
 3120: 5 value foo
 3121: foo .
 3122: 7 to foo
 3123: foo .
 3124: @end example
 3125: 
 3126: @quotation Assignment
 3127: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3128: XT (at the start the XT of @code{abort}), and upon execution
 3129: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3130: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3131: recursion is one application of @code{defer}.
 3132: @end quotation
 3133: 
 3134: Reference: @ref{User-defined Defining Words}.
 3135: 
 3136: 
 3137: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3138: @section Arrays and Records
 3139: @cindex arrays tutorial
 3140: @cindex records tutorial
 3141: @cindex structs tutorial
 3142: 
 3143: Forth has no standard words for defining data structures such as arrays
 3144: and records (structs in C terminology), but you can build them yourself
 3145: based on address arithmetic.  You can also define words for defining
 3146: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3147: 
 3148: One of the first projects a Forth newcomer sets out upon when learning
 3149: about defining words is an array defining word (possibly for
 3150: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3151: learn something from it.  However, don't be disappointed when you later
 3152: learn that you have little use for these words (inappropriate use would
 3153: be even worse).  I have not found a set of useful array words yet;
 3154: the needs are just too diverse, and named, global arrays (the result of
 3155: naive use of defining words) are often not flexible enough (e.g.,
 3156: consider how to pass them as parameters).  Another such project is a set
 3157: of words to help dealing with strings.
 3158: 
 3159: On the other hand, there is a useful set of record words, and it has
 3160: been defined in @file{compat/struct.fs}; these words are predefined in
 3161: Gforth.  They are explained in depth elsewhere in this manual (see
 3162: @pxref{Structures}).  The @code{simple-field} example above is
 3163: simplified variant of fields in this package.
 3164: 
 3165: 
 3166: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3167: @section @code{POSTPONE}
 3168: @cindex postpone tutorial
 3169: 
 3170: You can compile the compilation semantics (instead of compiling the
 3171: interpretation semantics) of a word with @code{POSTPONE}:
 3172: 
 3173: @example
 3174: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3175:  POSTPONE + ; immediate
 3176: : foo ( n1 n2 -- n )
 3177:  MY-+ ;
 3178: 1 2 foo .
 3179: see foo
 3180: @end example
 3181: 
 3182: During the definition of @code{foo} the text interpreter performs the
 3183: compilation semantics of @code{MY-+}, which performs the compilation
 3184: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3185: 
 3186: This example also displays separate stack comments for the compilation
 3187: semantics and for the stack effect of the compiled code.  For words with
 3188: default compilation semantics these stack effects are usually not
 3189: displayed; the stack effect of the compilation semantics is always
 3190: @code{( -- )} for these words, the stack effect for the compiled code is
 3191: the stack effect of the interpretation semantics.
 3192: 
 3193: Note that the state of the interpreter does not come into play when
 3194: performing the compilation semantics in this way.  You can also perform
 3195: it interpretively, e.g.:
 3196: 
 3197: @example
 3198: : foo2 ( n1 n2 -- n )
 3199:  [ MY-+ ] ;
 3200: 1 2 foo .
 3201: see foo
 3202: @end example
 3203: 
 3204: However, there are some broken Forth systems where this does not always
 3205: work, and therefore this practice was been declared non-standard in
 3206: 1999.
 3207: @c !! repair.fs
 3208: 
 3209: Here is another example for using @code{POSTPONE}:
 3210: 
 3211: @example
 3212: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3213:  POSTPONE negate POSTPONE + ; immediate compile-only
 3214: : bar ( n1 n2 -- n )
 3215:   MY-- ;
 3216: 2 1 bar .
 3217: see bar
 3218: @end example
 3219: 
 3220: You can define @code{ENDIF} in this way:
 3221: 
 3222: @example
 3223: : ENDIF ( Compilation: orig -- )
 3224:   POSTPONE then ; immediate
 3225: @end example
 3226: 
 3227: @quotation Assignment
 3228: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3229: @code{2dup}, but compiles @code{over over}.
 3230: @end quotation
 3231: 
 3232: @c !! @xref{Macros} for reference
 3233: 
 3234: 
 3235: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3236: @section @code{Literal}
 3237: @cindex literal tutorial
 3238: 
 3239: You cannot @code{POSTPONE} numbers:
 3240: 
 3241: @example
 3242: : [FOO] POSTPONE 500 ; immediate
 3243: @end example
 3244: 
 3245: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3246: 
 3247: @example
 3248: : [FOO] ( compilation: --; run-time: -- n )
 3249:   500 POSTPONE literal ; immediate
 3250: 
 3251: : flip [FOO] ;
 3252: flip .
 3253: see flip
 3254: @end example
 3255: 
 3256: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3257: semantics are executed) and pushes it at run-time (when the code it
 3258: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3259: number computed at compile time into the current word:
 3260: 
 3261: @example
 3262: : bar ( -- n )
 3263:   [ 2 2 + ] literal ;
 3264: see bar
 3265: @end example
 3266: 
 3267: @quotation Assignment
 3268: Write @code{]L} which allows writing the example above as @code{: bar (
 3269: -- n ) [ 2 2 + ]L ;}
 3270: @end quotation
 3271: 
 3272: @c !! @xref{Macros} for reference
 3273: 
 3274: 
 3275: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3276: @section Advanced macros
 3277: @cindex macros, advanced tutorial
 3278: @cindex run-time code generation, tutorial
 3279: 
 3280: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3281: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3282: expensive operation in some Forth implementations.  You can use
 3283: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3284: and produce a word that contains the word to be performed directly:
 3285: 
 3286: @c use ]] ... [[
 3287: @example
 3288: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3289: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3290: \ array beginning at addr and containing u elements
 3291:   @{ xt @}
 3292:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3293:     POSTPONE i POSTPONE @@ xt compile,
 3294:   1 cells POSTPONE literal POSTPONE +loop ;
 3295: 
 3296: : sum-array ( addr u -- n )
 3297:  0 rot rot [ ' + compile-map-array ] ;
 3298: see sum-array
 3299: a 5 sum-array .
 3300: @end example
 3301: 
 3302: You can use the full power of Forth for generating the code; here's an
 3303: example where the code is generated in a loop:
 3304: 
 3305: @example
 3306: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3307: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3308:   POSTPONE tuck POSTPONE @@
 3309:   POSTPONE literal POSTPONE * POSTPONE +
 3310:   POSTPONE swap POSTPONE cell+ ;
 3311: 
 3312: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3313: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3314:   0 postpone literal postpone swap
 3315:   [ ' compile-vmul-step compile-map-array ]
 3316:   postpone drop ;
 3317: see compile-vmul
 3318: 
 3319: : a-vmul ( addr -- n )
 3320: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3321:  [ a 5 compile-vmul ] ;
 3322: see a-vmul
 3323: a a-vmul .
 3324: @end example
 3325: 
 3326: This example uses @code{compile-map-array} to show off, but you could
 3327: also use @code{map-array} instead (try it now!).
 3328: 
 3329: You can use this technique for efficient multiplication of large
 3330: matrices.  In matrix multiplication, you multiply every line of one
 3331: matrix with every column of the other matrix.  You can generate the code
 3332: for one line once, and use it for every column.  The only downside of
 3333: this technique is that it is cumbersome to recover the memory consumed
 3334: by the generated code when you are done (and in more complicated cases
 3335: it is not possible portably).
 3336: 
 3337: @c !! @xref{Macros} for reference
 3338: 
 3339: 
 3340: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3341: @section Compilation Tokens
 3342: @cindex compilation tokens, tutorial
 3343: @cindex CT, tutorial
 3344: 
 3345: This section is Gforth-specific.  You can skip it.
 3346: 
 3347: @code{' word compile,} compiles the interpretation semantics.  For words
 3348: with default compilation semantics this is the same as performing the
 3349: compilation semantics.  To represent the compilation semantics of other
 3350: words (e.g., words like @code{if} that have no interpretation
 3351: semantics), Gforth has the concept of a compilation token (CT,
 3352: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3353: You can perform the compilation semantics represented by a CT with
 3354: @code{execute}:
 3355: 
 3356: @example
 3357: : foo2 ( n1 n2 -- n )
 3358:    [ comp' + execute ] ;
 3359: see foo
 3360: @end example
 3361: 
 3362: You can compile the compilation semantics represented by a CT with
 3363: @code{postpone,}:
 3364: 
 3365: @example
 3366: : foo3 ( -- )
 3367:   [ comp' + postpone, ] ;
 3368: see foo3
 3369: @end example
 3370: 
 3371: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3372: @code{comp'} is particularly useful for words that have no
 3373: interpretation semantics:
 3374: 
 3375: @example
 3376: ' if
 3377: comp' if .s 2drop
 3378: @end example
 3379: 
 3380: Reference: @ref{Tokens for Words}.
 3381: 
 3382: 
 3383: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3384: @section Wordlists and Search Order
 3385: @cindex wordlists tutorial
 3386: @cindex search order, tutorial
 3387: 
 3388: The dictionary is not just a memory area that allows you to allocate
 3389: memory with @code{allot}, it also contains the Forth words, arranged in
 3390: several wordlists.  When searching for a word in a wordlist,
 3391: conceptually you start searching at the youngest and proceed towards
 3392: older words (in reality most systems nowadays use hash-tables); i.e., if
 3393: you define a word with the same name as an older word, the new word
 3394: shadows the older word.
 3395: 
 3396: Which wordlists are searched in which order is determined by the search
 3397: order.  You can display the search order with @code{order}.  It displays
 3398: first the search order, starting with the wordlist searched first, then
 3399: it displays the wordlist that will contain newly defined words.
 3400: 
 3401: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3402: 
 3403: @example
 3404: wordlist constant mywords
 3405: @end example
 3406: 
 3407: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3408: defined words (the @emph{current} wordlist):
 3409: 
 3410: @example
 3411: mywords set-current
 3412: order
 3413: @end example
 3414: 
 3415: Gforth does not display a name for the wordlist in @code{mywords}
 3416: because this wordlist was created anonymously with @code{wordlist}.
 3417: 
 3418: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3419: you want to put something into a specific wordlist without overall
 3420: effect on the current wordlist, this typically looks like this:
 3421: 
 3422: @example
 3423: get-current mywords set-current ( wid )
 3424: create someword
 3425: ( wid ) set-current
 3426: @end example
 3427: 
 3428: You can write the search order with @code{set-order ( wid1 .. widn n --
 3429: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3430: searched wordlist is topmost.
 3431: 
 3432: @example
 3433: get-order mywords swap 1+ set-order
 3434: order
 3435: @end example
 3436: 
 3437: Yes, the order of wordlists in the output of @code{order} is reversed
 3438: from stack comments and the output of @code{.s} and thus unintuitive.
 3439: 
 3440: @quotation Assignment
 3441: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3442: wordlist to the search order.  Define @code{previous ( -- )}, which
 3443: removes the first searched wordlist from the search order.  Experiment
 3444: with boundary conditions (you will see some crashes or situations that
 3445: are hard or impossible to leave).
 3446: @end quotation
 3447: 
 3448: The search order is a powerful foundation for providing features similar
 3449: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3450: programs in this way has disadvantages for debugging and reuse/factoring
 3451: that overcome the advantages in my experience (I don't do huge projects,
 3452: though).  These disadvantages are not so clear in other
 3453: languages/programming environments, because these languages are not so
 3454: strong in debugging and reuse.
 3455: 
 3456: @c !! example
 3457: 
 3458: Reference: @ref{Word Lists}.
 3459: 
 3460: @c ******************************************************************
 3461: @node Introduction, Words, Tutorial, Top
 3462: @comment node-name,     next,           previous, up
 3463: @chapter An Introduction to ANS Forth
 3464: @cindex Forth - an introduction
 3465: 
 3466: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3467: that it is slower-paced in its examples, but uses them to dive deep into
 3468: explaining Forth internals (not covered by the Tutorial).  Apart from
 3469: that, this chapter covers far less material.  It is suitable for reading
 3470: without using a computer.
 3471: 
 3472: The primary purpose of this manual is to document Gforth. However, since
 3473: Forth is not a widely-known language and there is a lack of up-to-date
 3474: teaching material, it seems worthwhile to provide some introductory
 3475: material.  For other sources of Forth-related
 3476: information, see @ref{Forth-related information}.
 3477: 
 3478: The examples in this section should work on any ANS Forth; the
 3479: output shown was produced using Gforth. Each example attempts to
 3480: reproduce the exact output that Gforth produces. If you try out the
 3481: examples (and you should), what you should type is shown @kbd{like this}
 3482: and Gforth's response is shown @code{like this}. The single exception is
 3483: that, where the example shows @key{RET} it means that you should
 3484: press the ``carriage return'' key. Unfortunately, some output formats for
 3485: this manual cannot show the difference between @kbd{this} and
 3486: @code{this} which will make trying out the examples harder (but not
 3487: impossible).
 3488: 
 3489: Forth is an unusual language. It provides an interactive development
 3490: environment which includes both an interpreter and compiler. Forth
 3491: programming style encourages you to break a problem down into many
 3492: @cindex factoring
 3493: small fragments (@dfn{factoring}), and then to develop and test each
 3494: fragment interactively. Forth advocates assert that breaking the
 3495: edit-compile-test cycle used by conventional programming languages can
 3496: lead to great productivity improvements.
 3497: 
 3498: @menu
 3499: * Introducing the Text Interpreter::  
 3500: * Stacks and Postfix notation::  
 3501: * Your first definition::       
 3502: * How does that work?::         
 3503: * Forth is written in Forth::   
 3504: * Review - elements of a Forth system::  
 3505: * Where to go next::            
 3506: * Exercises::                   
 3507: @end menu
 3508: 
 3509: @comment ----------------------------------------------
 3510: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3511: @section Introducing the Text Interpreter
 3512: @cindex text interpreter
 3513: @cindex outer interpreter
 3514: 
 3515: @c IMO this is too detailed and the pace is too slow for
 3516: @c an introduction.  If you know German, take a look at
 3517: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3518: @c to see how I do it - anton 
 3519: 
 3520: @c nac-> Where I have accepted your comments 100% and modified the text
 3521: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3522: @c response like this to attempt to rationalise what I have done. Of
 3523: @c course, this is a very clumsy mechanism for something that would be
 3524: @c done far more efficiently over a beer. Please delete any dialogue
 3525: @c you consider closed.
 3526: 
 3527: When you invoke the Forth image, you will see a startup banner printed
 3528: and nothing else (if you have Gforth installed on your system, try
 3529: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3530: its command line interpreter, which is called the @dfn{Text Interpreter}
 3531: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3532: about the text interpreter as you read through this chapter, for more
 3533: detail @pxref{The Text Interpreter}).
 3534: 
 3535: Although it's not obvious, Forth is actually waiting for your
 3536: input. Type a number and press the @key{RET} key:
 3537: 
 3538: @example
 3539: @kbd{45@key{RET}}  ok
 3540: @end example
 3541: 
 3542: Rather than give you a prompt to invite you to input something, the text
 3543: interpreter prints a status message @i{after} it has processed a line
 3544: of input. The status message in this case (``@code{ ok}'' followed by
 3545: carriage-return) indicates that the text interpreter was able to process
 3546: all of your input successfully. Now type something illegal:
 3547: 
 3548: @example
 3549: @kbd{qwer341@key{RET}}
 3550: *the terminal*:2: Undefined word
 3551: >>>qwer341<<<
 3552: Backtrace:
 3553: $2A95B42A20 throw 
 3554: $2A95B57FB8 no.extensions 
 3555: @end example
 3556: 
 3557: The exact text, other than the ``Undefined word'' may differ slightly
 3558: on your system, but the effect is the same; when the text interpreter
 3559: detects an error, it discards any remaining text on a line, resets
 3560: certain internal state and prints an error message. For a detailed
 3561: description of error messages see @ref{Error messages}.
 3562: 
 3563: The text interpreter waits for you to press carriage-return, and then
 3564: processes your input line. Starting at the beginning of the line, it
 3565: breaks the line into groups of characters separated by spaces. For each
 3566: group of characters in turn, it makes two attempts to do something:
 3567: 
 3568: @itemize @bullet
 3569: @item
 3570: @cindex name dictionary
 3571: It tries to treat it as a command. It does this by searching a @dfn{name
 3572: dictionary}. If the group of characters matches an entry in the name
 3573: dictionary, the name dictionary provides the text interpreter with
 3574: information that allows the text interpreter perform some actions. In
 3575: Forth jargon, we say that the group
 3576: @cindex word
 3577: @cindex definition
 3578: @cindex execution token
 3579: @cindex xt
 3580: of characters names a @dfn{word}, that the dictionary search returns an
 3581: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3582: word, and that the text interpreter executes the xt. Often, the terms
 3583: @dfn{word} and @dfn{definition} are used interchangeably.
 3584: @item
 3585: If the text interpreter fails to find a match in the name dictionary, it
 3586: tries to treat the group of characters as a number in the current number
 3587: base (when you start up Forth, the current number base is base 10). If
 3588: the group of characters legitimately represents a number, the text
 3589: interpreter pushes the number onto a stack (we'll learn more about that
 3590: in the next section).
 3591: @end itemize
 3592: 
 3593: If the text interpreter is unable to do either of these things with any
 3594: group of characters, it discards the group of characters and the rest of
 3595: the line, then prints an error message. If the text interpreter reaches
 3596: the end of the line without error, it prints the status message ``@code{ ok}''
 3597: followed by carriage-return.
 3598: 
 3599: This is the simplest command we can give to the text interpreter:
 3600: 
 3601: @example
 3602: @key{RET}  ok
 3603: @end example
 3604: 
 3605: The text interpreter did everything we asked it to do (nothing) without
 3606: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3607: command:
 3608: 
 3609: @example
 3610: @kbd{12 dup fred dup@key{RET}}
 3611: *the terminal*:3: Undefined word
 3612: 12 dup >>>fred<<< dup
 3613: Backtrace:
 3614: $2A95B42A20 throw 
 3615: $2A95B57FB8 no.extensions 
 3616: @end example
 3617: 
 3618: When you press the carriage-return key, the text interpreter starts to
 3619: work its way along the line:
 3620: 
 3621: @itemize @bullet
 3622: @item
 3623: When it gets to the space after the @code{2}, it takes the group of
 3624: characters @code{12} and looks them up in the name
 3625: dictionary@footnote{We can't tell if it found them or not, but assume
 3626: for now that it did not}. There is no match for this group of characters
 3627: in the name dictionary, so it tries to treat them as a number. It is
 3628: able to do this successfully, so it puts the number, 12, ``on the stack''
 3629: (whatever that means).
 3630: @item
 3631: The text interpreter resumes scanning the line and gets the next group
 3632: of characters, @code{dup}. It looks it up in the name dictionary and
 3633: (you'll have to take my word for this) finds it, and executes the word
 3634: @code{dup} (whatever that means).
 3635: @item
 3636: Once again, the text interpreter resumes scanning the line and gets the
 3637: group of characters @code{fred}. It looks them up in the name
 3638: dictionary, but can't find them. It tries to treat them as a number, but
 3639: they don't represent any legal number.
 3640: @end itemize
 3641: 
 3642: At this point, the text interpreter gives up and prints an error
 3643: message. The error message shows exactly how far the text interpreter
 3644: got in processing the line. In particular, it shows that the text
 3645: interpreter made no attempt to do anything with the final character
 3646: group, @code{dup}, even though we have good reason to believe that the
 3647: text interpreter would have no problem looking that word up and
 3648: executing it a second time.
 3649: 
 3650: 
 3651: @comment ----------------------------------------------
 3652: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3653: @section Stacks, postfix notation and parameter passing
 3654: @cindex text interpreter
 3655: @cindex outer interpreter
 3656: 
 3657: In procedural programming languages (like C and Pascal), the
 3658: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3659: functions or procedures are called with @dfn{explicit parameters}. For
 3660: example, in C we might write:
 3661: 
 3662: @example
 3663: total = total + new_volume(length,height,depth);
 3664: @end example
 3665: 
 3666: @noindent
 3667: where new_volume is a function-call to another piece of code, and total,
 3668: length, height and depth are all variables. length, height and depth are
 3669: parameters to the function-call.
 3670: 
 3671: In Forth, the equivalent of the function or procedure is the
 3672: @dfn{definition} and parameters are implicitly passed between
 3673: definitions using a shared stack that is visible to the
 3674: programmer. Although Forth does support variables, the existence of the
 3675: stack means that they are used far less often than in most other
 3676: programming languages. When the text interpreter encounters a number, it
 3677: will place (@dfn{push}) it on the stack. There are several stacks (the
 3678: actual number is implementation-dependent ...) and the particular stack
 3679: used for any operation is implied unambiguously by the operation being
 3680: performed. The stack used for all integer operations is called the @dfn{data
 3681: stack} and, since this is the stack used most commonly, references to
 3682: ``the data stack'' are often abbreviated to ``the stack''.
 3683: 
 3684: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3685: 
 3686: @example
 3687: @kbd{1 2 3@key{RET}}  ok
 3688: @end example
 3689: 
 3690: Then this instructs the text interpreter to placed three numbers on the
 3691: (data) stack. An analogy for the behaviour of the stack is to take a
 3692: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3693: the table. The 3 was the last card onto the pile (``last-in'') and if
 3694: you take a card off the pile then, unless you're prepared to fiddle a
 3695: bit, the card that you take off will be the 3 (``first-out''). The
 3696: number that will be first-out of the stack is called the @dfn{top of
 3697: stack}, which
 3698: @cindex TOS definition
 3699: is often abbreviated to @dfn{TOS}.
 3700: 
 3701: To understand how parameters are passed in Forth, consider the
 3702: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3703: be surprised to learn that this definition performs addition. More
 3704: precisely, it adds two number together and produces a result. Where does
 3705: it get the two numbers from? It takes the top two numbers off the
 3706: stack. Where does it place the result? On the stack. You can act-out the
 3707: behaviour of @code{+} with your playing cards like this:
 3708: 
 3709: @itemize @bullet
 3710: @item
 3711: Pick up two cards from the stack on the table
 3712: @item
 3713: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3714: numbers''
 3715: @item
 3716: Decide that the answer is 5
 3717: @item
 3718: Shuffle the two cards back into the pack and find a 5
 3719: @item
 3720: Put a 5 on the remaining ace that's on the table.
 3721: @end itemize
 3722: 
 3723: If you don't have a pack of cards handy but you do have Forth running,
 3724: you can use the definition @code{.s} to show the current state of the stack,
 3725: without affecting the stack. Type:
 3726: 
 3727: @example
 3728: @kbd{clearstacks 1 2 3@key{RET}} ok
 3729: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3730: @end example
 3731: 
 3732: The text interpreter looks up the word @code{clearstacks} and executes
 3733: it; it tidies up the stacks and removes any entries that may have been
 3734: left on it by earlier examples. The text interpreter pushes each of the
 3735: three numbers in turn onto the stack. Finally, the text interpreter
 3736: looks up the word @code{.s} and executes it. The effect of executing
 3737: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3738: followed by a list of all the items on the stack; the item on the far
 3739: right-hand side is the TOS.
 3740: 
 3741: You can now type:
 3742: 
 3743: @example
 3744: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3745: @end example
 3746: 
 3747: @noindent
 3748: which is correct; there are now 2 items on the stack and the result of
 3749: the addition is 5.
 3750: 
 3751: If you're playing with cards, try doing a second addition: pick up the
 3752: two cards, work out that their sum is 6, shuffle them into the pack,
 3753: look for a 6 and place that on the table. You now have just one item on
 3754: the stack. What happens if you try to do a third addition? Pick up the
 3755: first card, pick up the second card -- ah! There is no second card. This
 3756: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3757: do the same thing with Forth it often reports an error (probably a Stack
 3758: Underflow or an Invalid Memory Address error).
 3759: 
 3760: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3761: which simply accepts that there is a finite amount of storage space
 3762: reserved for the stack. To stretch the playing card analogy, if you had
 3763: enough packs of cards and you piled the cards up on the table, you would
 3764: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3765: allows you to set the maximum size of the stacks. In general, the only
 3766: time that you will get a stack overflow is because a definition has a
 3767: bug in it and is generating data on the stack uncontrollably.
 3768: 
 3769: There's one final use for the playing card analogy. If you model your
 3770: stack using a pack of playing cards, the maximum number of items on
 3771: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3772: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3773: possible numbers are positive integer numbers 1 through 13; you can't
 3774: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3775: think about some of the cards, you can accommodate different
 3776: numbers. For example, you could think of the Jack as representing 0,
 3777: the Queen as representing -1 and the King as representing -2. Your
 3778: @i{range} remains unchanged (you can still only represent a total of 13
 3779: numbers) but the numbers that you can represent are -2 through 10.
 3780: 
 3781: In that analogy, the limit was the amount of information that a single
 3782: stack entry could hold, and Forth has a similar limit. In Forth, the
 3783: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3784: implementation dependent and affects the maximum value that a stack
 3785: entry can hold. A Standard Forth provides a cell size of at least
 3786: 16-bits, and most desktop systems use a cell size of 32-bits.
 3787: 
 3788: Forth does not do any type checking for you, so you are free to
 3789: manipulate and combine stack items in any way you wish. A convenient way
 3790: of treating stack items is as 2's complement signed integers, and that
 3791: is what Standard words like @code{+} do. Therefore you can type:
 3792: 
 3793: @example
 3794: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3795: @end example
 3796: 
 3797: If you use numbers and definitions like @code{+} in order to turn Forth
 3798: into a great big pocket calculator, you will realise that it's rather
 3799: different from a normal calculator. Rather than typing 2 + 3 = you had
 3800: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3801: result). The terminology used to describe this difference is to say that
 3802: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3803: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3804: operators are separate), also called @dfn{Reverse Polish Notation}.
 3805: 
 3806: Whilst postfix notation might look confusing to begin with, it has
 3807: several important advantages:
 3808: 
 3809: @itemize @bullet
 3810: @item
 3811: it is unambiguous
 3812: @item
 3813: it is more concise
 3814: @item
 3815: it fits naturally with a stack-based system
 3816: @end itemize
 3817: 
 3818: To examine these claims in more detail, consider these sums:
 3819: 
 3820: @example
 3821: 6 + 5 * 4 =
 3822: 4 * 5 + 6 =
 3823: @end example
 3824: 
 3825: If you're just learning maths or your maths is very rusty, you will
 3826: probably come up with the answer 44 for the first and 26 for the
 3827: second. If you are a bit of a whizz at maths you will remember the
 3828: @i{convention} that multiplication takes precendence over addition, and
 3829: you'd come up with the answer 26 both times. To explain the answer 26
 3830: to someone who got the answer 44, you'd probably rewrite the first sum
 3831: like this:
 3832: 
 3833: @example
 3834: 6 + (5 * 4) =
 3835: @end example
 3836: 
 3837: If what you really wanted was to perform the addition before the
 3838: multiplication, you would have to use parentheses to force it.
 3839: 
 3840: If you did the first two sums on a pocket calculator you would probably
 3841: get the right answers, unless you were very cautious and entered them using
 3842: these keystroke sequences:
 3843: 
 3844: 6 + 5 = * 4 =
 3845: 4 * 5 = + 6 =
 3846: 
 3847: Postfix notation is unambiguous because the order that the operators
 3848: are applied is always explicit; that also means that parentheses are
 3849: never required. The operators are @i{active} (the act of quoting the
 3850: operator makes the operation occur) which removes the need for ``=''.
 3851: 
 3852: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3853: equivalent ways:
 3854: 
 3855: @example
 3856: 6 5 4 * +      or:
 3857: 5 4 * 6 +
 3858: @end example
 3859: 
 3860: An important thing that you should notice about this notation is that
 3861: the @i{order} of the numbers does not change; if you want to subtract
 3862: 2 from 10 you type @code{10 2 -}.
 3863: 
 3864: The reason that Forth uses postfix notation is very simple to explain: it
 3865: makes the implementation extremely simple, and it follows naturally from
 3866: using the stack as a mechanism for passing parameters. Another way of
 3867: thinking about this is to realise that all Forth definitions are
 3868: @i{active}; they execute as they are encountered by the text
 3869: interpreter. The result of this is that the syntax of Forth is trivially
 3870: simple.
 3871: 
 3872: 
 3873: 
 3874: @comment ----------------------------------------------
 3875: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3876: @section Your first Forth definition
 3877: @cindex first definition
 3878: 
 3879: Until now, the examples we've seen have been trivial; we've just been
 3880: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3881: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3882: again@footnote{That's not quite true. If you press the up-arrow key on
 3883: your keyboard you should be able to scroll back to any earlier command,
 3884: edit it and re-enter it.} In this section we'll see how to add new
 3885: words to Forth's vocabulary.
 3886: 
 3887: The easiest way to create a new word is to use a @dfn{colon
 3888: definition}. We'll define a few and try them out before worrying too
 3889: much about how they work. Try typing in these examples; be careful to
 3890: copy the spaces accurately:
 3891: 
 3892: @example
 3893: : add-two 2 + . ;
 3894: : greet ." Hello and welcome" ;
 3895: : demo 5 add-two ;
 3896: @end example
 3897: 
 3898: @noindent
 3899: Now try them out:
 3900: 
 3901: @example
 3902: @kbd{greet@key{RET}} Hello and welcome  ok
 3903: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3904: @kbd{4 add-two@key{RET}} 6  ok
 3905: @kbd{demo@key{RET}} 7  ok
 3906: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3907: @end example
 3908: 
 3909: The first new thing that we've introduced here is the pair of words
 3910: @code{:} and @code{;}. These are used to start and terminate a new
 3911: definition, respectively. The first word after the @code{:} is the name
 3912: for the new definition.
 3913: 
 3914: As you can see from the examples, a definition is built up of words that
 3915: have already been defined; Forth makes no distinction between
 3916: definitions that existed when you started the system up, and those that
 3917: you define yourself.
 3918: 
 3919: The examples also introduce the words @code{.} (dot), @code{."}
 3920: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3921: the stack and displays it. It's like @code{.s} except that it only
 3922: displays the top item of the stack and it is destructive; after it has
 3923: executed, the number is no longer on the stack. There is always one
 3924: space printed after the number, and no spaces before it. Dot-quote
 3925: defines a string (a sequence of characters) that will be printed when
 3926: the word is executed. The string can contain any printable characters
 3927: except @code{"}. A @code{"} has a special function; it is not a Forth
 3928: word but it acts as a delimiter (the way that delimiters work is
 3929: described in the next section). Finally, @code{dup} duplicates the value
 3930: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3931: 
 3932: We already know that the text interpreter searches through the
 3933: dictionary to locate names. If you've followed the examples earlier, you
 3934: will already have a definition called @code{add-two}. Lets try modifying
 3935: it by typing in a new definition:
 3936: 
 3937: @example
 3938: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3939: @end example
 3940: 
 3941: Forth recognised that we were defining a word that already exists, and
 3942: printed a message to warn us of that fact. Let's try out the new
 3943: definition:
 3944: 
 3945: @example
 3946: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3947: @end example
 3948: 
 3949: @noindent
 3950: All that we've actually done here, though, is to create a new
 3951: definition, with a particular name. The fact that there was already a
 3952: definition with the same name did not make any difference to the way
 3953: that the new definition was created (except that Forth printed a warning
 3954: message). The old definition of add-two still exists (try @code{demo}
 3955: again to see that this is true). Any new definition will use the new
 3956: definition of @code{add-two}, but old definitions continue to use the
 3957: version that already existed at the time that they were @code{compiled}.
 3958: 
 3959: Before you go on to the next section, try defining and redefining some
 3960: words of your own.
 3961: 
 3962: @comment ----------------------------------------------
 3963: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3964: @section How does that work?
 3965: @cindex parsing words
 3966: 
 3967: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3968: 
 3969: @c Is it a good idea to talk about the interpretation semantics of a
 3970: @c number? We don't have an xt to go along with it. - anton
 3971: 
 3972: @c Now that I have eliminated execution semantics, I wonder if it would not
 3973: @c be better to keep them (or add run-time semantics), to make it easier to
 3974: @c explain what compilation semantics usually does. - anton
 3975: 
 3976: @c nac-> I removed the term ``default compilation sematics'' from the
 3977: @c introductory chapter. Removing ``execution semantics'' was making
 3978: @c everything simpler to explain, then I think the use of this term made
 3979: @c everything more complex again. I replaced it with ``default
 3980: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3981: @c ``a definition that has neither the immediate nor the compile-only
 3982: @c flag set''.
 3983: 
 3984: @c anton: I have eliminated default semantics (except in one place where it
 3985: @c means "default interpretation and compilation semantics"), because it
 3986: @c makes no sense in the presence of combined words.  I reverted to
 3987: @c "execution semantics" where necessary.
 3988: 
 3989: @c nac-> I reworded big chunks of the ``how does that work''
 3990: @c section (and, unusually for me, I think I even made it shorter!).  See
 3991: @c what you think -- I know I have not addressed your primary concern
 3992: @c that it is too heavy-going for an introduction. From what I understood
 3993: @c of your course notes it looks as though they might be a good framework. 
 3994: @c Things that I've tried to capture here are some things that came as a
 3995: @c great revelation here when I first understood them. Also, I like the
 3996: @c fact that a very simple code example shows up almost all of the issues
 3997: @c that you need to understand to see how Forth works. That's unique and
 3998: @c worthwhile to emphasise.
 3999: 
 4000: @c anton: I think it's a good idea to present the details, especially those
 4001: @c that you found to be a revelation, and probably the tutorial tries to be
 4002: @c too superficial and does not get some of the things across that make
 4003: @c Forth special.  I do believe that most of the time these things should
 4004: @c be discussed at the end of a section or in separate sections instead of
 4005: @c in the middle of a section (e.g., the stuff you added in "User-defined
 4006: @c defining words" leads in a completely different direction from the rest
 4007: @c of the section).
 4008: 
 4009: Now we're going to take another look at the definition of @code{add-two}
 4010: from the previous section. From our knowledge of the way that the text
 4011: interpreter works, we would have expected this result when we tried to
 4012: define @code{add-two}:
 4013: 
 4014: @example
 4015: @kbd{: add-two 2 + . ;@key{RET}}
 4016: *the terminal*:4: Undefined word
 4017: : >>>add-two<<< 2 + . ;
 4018: @end example
 4019: 
 4020: The reason that this didn't happen is bound up in the way that @code{:}
 4021: works. The word @code{:} does two special things. The first special
 4022: thing that it does prevents the text interpreter from ever seeing the
 4023: characters @code{add-two}. The text interpreter uses a variable called
 4024: @cindex modifying >IN
 4025: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 4026: input line. When it encounters the word @code{:} it behaves in exactly
 4027: the same way as it does for any other word; it looks it up in the name
 4028: dictionary, finds its xt and executes it. When @code{:} executes, it
 4029: looks at the input buffer, finds the word @code{add-two} and advances the
 4030: value of @code{>IN} to point past it. It then does some other stuff
 4031: associated with creating the new definition (including creating an entry
 4032: for @code{add-two} in the name dictionary). When the execution of @code{:}
 4033: completes, control returns to the text interpreter, which is oblivious
 4034: to the fact that it has been tricked into ignoring part of the input
 4035: line.
 4036: 
 4037: @cindex parsing words
 4038: Words like @code{:} -- words that advance the value of @code{>IN} and so
 4039: prevent the text interpreter from acting on the whole of the input line
 4040: -- are called @dfn{parsing words}.
 4041: 
 4042: @cindex @code{state} - effect on the text interpreter
 4043: @cindex text interpreter - effect of state
 4044: The second special thing that @code{:} does is change the value of a
 4045: variable called @code{state}, which affects the way that the text
 4046: interpreter behaves. When Gforth starts up, @code{state} has the value
 4047: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 4048: colon definition (started with @code{:}), @code{state} is set to -1 and
 4049: the text interpreter is said to be @dfn{compiling}.
 4050: 
 4051: In this example, the text interpreter is compiling when it processes the
 4052: string ``@code{2 + . ;}''. It still breaks the string down into
 4053: character sequences in the same way. However, instead of pushing the
 4054: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 4055: into the definition of @code{add-two} that will make the number @code{2} get
 4056: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 4057: the behaviours of @code{+} and @code{.} are also compiled into the
 4058: definition.
 4059: 
 4060: One category of words don't get compiled. These so-called @dfn{immediate
 4061: words} get executed (performed @i{now}) regardless of whether the text
 4062: interpreter is interpreting or compiling. The word @code{;} is an
 4063: immediate word. Rather than being compiled into the definition, it
 4064: executes. Its effect is to terminate the current definition, which
 4065: includes changing the value of @code{state} back to 0.
 4066: 
 4067: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 4068: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 4069: definition.
 4070: 
 4071: In Forth, every word or number can be described in terms of two
 4072: properties:
 4073: 
 4074: @itemize @bullet
 4075: @item
 4076: @cindex interpretation semantics
 4077: Its @dfn{interpretation semantics} describe how it will behave when the
 4078: text interpreter encounters it in @dfn{interpret} state. The
 4079: interpretation semantics of a word are represented by an @dfn{execution
 4080: token}.
 4081: @item
 4082: @cindex compilation semantics
 4083: Its @dfn{compilation semantics} describe how it will behave when the
 4084: text interpreter encounters it in @dfn{compile} state. The compilation
 4085: semantics of a word are represented in an implementation-dependent way;
 4086: Gforth uses a @dfn{compilation token}.
 4087: @end itemize
 4088: 
 4089: @noindent
 4090: Numbers are always treated in a fixed way:
 4091: 
 4092: @itemize @bullet
 4093: @item
 4094: When the number is @dfn{interpreted}, its behaviour is to push the
 4095: number onto the stack.
 4096: @item
 4097: When the number is @dfn{compiled}, a piece of code is appended to the
 4098: current definition that pushes the number when it runs. (In other words,
 4099: the compilation semantics of a number are to postpone its interpretation
 4100: semantics until the run-time of the definition that it is being compiled
 4101: into.)
 4102: @end itemize
 4103: 
 4104: Words don't behave in such a regular way, but most have @i{default
 4105: semantics} which means that they behave like this:
 4106: 
 4107: @itemize @bullet
 4108: @item
 4109: The @dfn{interpretation semantics} of the word are to do something useful.
 4110: @item
 4111: The @dfn{compilation semantics} of the word are to append its
 4112: @dfn{interpretation semantics} to the current definition (so that its
 4113: run-time behaviour is to do something useful).
 4114: @end itemize
 4115: 
 4116: @cindex immediate words
 4117: The actual behaviour of any particular word can be controlled by using
 4118: the words @code{immediate} and @code{compile-only} when the word is
 4119: defined. These words set flags in the name dictionary entry of the most
 4120: recently defined word, and these flags are retrieved by the text
 4121: interpreter when it finds the word in the name dictionary.
 4122: 
 4123: A word that is marked as @dfn{immediate} has compilation semantics that
 4124: are identical to its interpretation semantics. In other words, it
 4125: behaves like this:
 4126: 
 4127: @itemize @bullet
 4128: @item
 4129: The @dfn{interpretation semantics} of the word are to do something useful.
 4130: @item
 4131: The @dfn{compilation semantics} of the word are to do something useful
 4132: (and actually the same thing); i.e., it is executed during compilation.
 4133: @end itemize
 4134: 
 4135: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4136: performing the interpretation semantics of the word directly; an attempt
 4137: to do so will generate an error. It is never necessary to use
 4138: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4139: provided by many implementations) but it is good etiquette to apply it
 4140: to a word that will not behave correctly (and might have unexpected
 4141: side-effects) in interpret state. For example, it is only legal to use
 4142: the conditional word @code{IF} within a definition. If you forget this
 4143: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4144: @code{compile-only} allows the text interpreter to generate a helpful
 4145: error message rather than subjecting you to the consequences of your
 4146: folly.
 4147: 
 4148: This example shows the difference between an immediate and a
 4149: non-immediate word:
 4150: 
 4151: @example
 4152: : show-state state @@ . ;
 4153: : show-state-now show-state ; immediate
 4154: : word1 show-state ;
 4155: : word2 show-state-now ;
 4156: @end example
 4157: 
 4158: The word @code{immediate} after the definition of @code{show-state-now}
 4159: makes that word an immediate word. These definitions introduce a new
 4160: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4161: variable, and leaves it on the stack. Therefore, the behaviour of
 4162: @code{show-state} is to print a number that represents the current value
 4163: of @code{state}.
 4164: 
 4165: When you execute @code{word1}, it prints the number 0, indicating that
 4166: the system is interpreting. When the text interpreter compiled the
 4167: definition of @code{word1}, it encountered @code{show-state} whose
 4168: compilation semantics are to append its interpretation semantics to the
 4169: current definition. When you execute @code{word1}, it performs the
 4170: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4171: (and therefore @code{show-state}) are executed, the system is
 4172: interpreting.
 4173: 
 4174: When you pressed @key{RET} after entering the definition of @code{word2},
 4175: you should have seen the number -1 printed, followed by ``@code{
 4176: ok}''. When the text interpreter compiled the definition of
 4177: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4178: whose compilation semantics are therefore to perform its interpretation
 4179: semantics. It is executed straight away (even before the text
 4180: interpreter has moved on to process another group of characters; the
 4181: @code{;} in this example). The effect of executing it are to display the
 4182: value of @code{state} @i{at the time that the definition of}
 4183: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4184: system is compiling at this time. If you execute @code{word2} it does
 4185: nothing at all.
 4186: 
 4187: @cindex @code{."}, how it works
 4188: Before leaving the subject of immediate words, consider the behaviour of
 4189: @code{."} in the definition of @code{greet}, in the previous
 4190: section. This word is both a parsing word and an immediate word. Notice
 4191: that there is a space between @code{."} and the start of the text
 4192: @code{Hello and welcome}, but that there is no space between the last
 4193: letter of @code{welcome} and the @code{"} character. The reason for this
 4194: is that @code{."} is a Forth word; it must have a space after it so that
 4195: the text interpreter can identify it. The @code{"} is not a Forth word;
 4196: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4197: is displayed, there is neither a space before the @code{H} nor after the
 4198: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4199: that @code{greet} is defined. When it executes, its behaviour is to
 4200: search forward in the input line looking for the delimiter. When it
 4201: finds the delimiter, it updates @code{>IN} to point past the
 4202: delimiter. It also compiles some magic code into the definition of
 4203: @code{greet}; the xt of a run-time routine that prints a text string. It
 4204: compiles the string @code{Hello and welcome} into memory so that it is
 4205: available to be printed later. When the text interpreter gains control,
 4206: the next word it finds in the input stream is @code{;} and so it
 4207: terminates the definition of @code{greet}.
 4208: 
 4209: 
 4210: @comment ----------------------------------------------
 4211: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4212: @section Forth is written in Forth
 4213: @cindex structure of Forth programs
 4214: 
 4215: When you start up a Forth compiler, a large number of definitions
 4216: already exist. In Forth, you develop a new application using bottom-up
 4217: programming techniques to create new definitions that are defined in
 4218: terms of existing definitions. As you create each definition you can
 4219: test and debug it interactively.
 4220: 
 4221: If you have tried out the examples in this section, you will probably
 4222: have typed them in by hand; when you leave Gforth, your definitions will
 4223: be lost. You can avoid this by using a text editor to enter Forth source
 4224: code into a file, and then loading code from the file using
 4225: @code{include} (@pxref{Forth source files}). A Forth source file is
 4226: processed by the text interpreter, just as though you had typed it in by
 4227: hand@footnote{Actually, there are some subtle differences -- see
 4228: @ref{The Text Interpreter}.}.
 4229: 
 4230: Gforth also supports the traditional Forth alternative to using text
 4231: files for program entry (@pxref{Blocks}).
 4232: 
 4233: In common with many, if not most, Forth compilers, most of Gforth is
 4234: actually written in Forth. All of the @file{.fs} files in the
 4235: installation directory@footnote{For example,
 4236: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4237: study to see examples of Forth programming.
 4238: 
 4239: Gforth maintains a history file that records every line that you type to
 4240: the text interpreter. This file is preserved between sessions, and is
 4241: used to provide a command-line recall facility. If you enter long
 4242: definitions by hand, you can use a text editor to paste them out of the
 4243: history file into a Forth source file for reuse at a later time
 4244: (for more information @pxref{Command-line editing}).
 4245: 
 4246: 
 4247: @comment ----------------------------------------------
 4248: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4249: @section Review - elements of a Forth system
 4250: @cindex elements of a Forth system
 4251: 
 4252: To summarise this chapter:
 4253: 
 4254: @itemize @bullet
 4255: @item
 4256: Forth programs use @dfn{factoring} to break a problem down into small
 4257: fragments called @dfn{words} or @dfn{definitions}.
 4258: @item
 4259: Forth program development is an interactive process.
 4260: @item
 4261: The main command loop that accepts input, and controls both
 4262: interpretation and compilation, is called the @dfn{text interpreter}
 4263: (also known as the @dfn{outer interpreter}).
 4264: @item
 4265: Forth has a very simple syntax, consisting of words and numbers
 4266: separated by spaces or carriage-return characters. Any additional syntax
 4267: is imposed by @dfn{parsing words}.
 4268: @item
 4269: Forth uses a stack to pass parameters between words. As a result, it
 4270: uses postfix notation.
 4271: @item
 4272: To use a word that has previously been defined, the text interpreter
 4273: searches for the word in the @dfn{name dictionary}.
 4274: @item
 4275: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4276: @item
 4277: The text interpreter uses the value of @code{state} to select between
 4278: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4279: semantics} of a word that it encounters.
 4280: @item
 4281: The relationship between the @dfn{interpretation semantics} and
 4282: @dfn{compilation semantics} for a word
 4283: depend upon the way in which the word was defined (for example, whether
 4284: it is an @dfn{immediate} word).
 4285: @item
 4286: Forth definitions can be implemented in Forth (called @dfn{high-level
 4287: definitions}) or in some other way (usually a lower-level language and
 4288: as a result often called @dfn{low-level definitions}, @dfn{code
 4289: definitions} or @dfn{primitives}).
 4290: @item
 4291: Many Forth systems are implemented mainly in Forth.
 4292: @end itemize
 4293: 
 4294: 
 4295: @comment ----------------------------------------------
 4296: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4297: @section Where To Go Next
 4298: @cindex where to go next
 4299: 
 4300: Amazing as it may seem, if you have read (and understood) this far, you
 4301: know almost all the fundamentals about the inner workings of a Forth
 4302: system. You certainly know enough to be able to read and understand the
 4303: rest of this manual and the ANS Forth document, to learn more about the
 4304: facilities that Forth in general and Gforth in particular provide. Even
 4305: scarier, you know almost enough to implement your own Forth system.
 4306: However, that's not a good idea just yet... better to try writing some
 4307: programs in Gforth.
 4308: 
 4309: Forth has such a rich vocabulary that it can be hard to know where to
 4310: start in learning it. This section suggests a few sets of words that are
 4311: enough to write small but useful programs. Use the word index in this
 4312: document to learn more about each word, then try it out and try to write
 4313: small definitions using it. Start by experimenting with these words:
 4314: 
 4315: @itemize @bullet
 4316: @item
 4317: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4318: @item
 4319: Comparison: @code{MIN MAX =}
 4320: @item
 4321: Logic: @code{AND OR XOR NOT}
 4322: @item
 4323: Stack manipulation: @code{DUP DROP SWAP OVER}
 4324: @item
 4325: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4326: @item
 4327: Input/Output: @code{. ." EMIT CR KEY}
 4328: @item
 4329: Defining words: @code{: ; CREATE}
 4330: @item
 4331: Memory allocation words: @code{ALLOT ,}
 4332: @item
 4333: Tools: @code{SEE WORDS .S MARKER}
 4334: @end itemize
 4335: 
 4336: When you have mastered those, go on to:
 4337: 
 4338: @itemize @bullet
 4339: @item
 4340: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4341: @item
 4342: Memory access: @code{@@ !}
 4343: @end itemize
 4344: 
 4345: When you have mastered these, there's nothing for it but to read through
 4346: the whole of this manual and find out what you've missed.
 4347: 
 4348: @comment ----------------------------------------------
 4349: @node Exercises,  , Where to go next, Introduction
 4350: @section Exercises
 4351: @cindex exercises
 4352: 
 4353: TODO: provide a set of programming excercises linked into the stuff done
 4354: already and into other sections of the manual. Provide solutions to all
 4355: the exercises in a .fs file in the distribution.
 4356: 
 4357: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4358: 
 4359: @c excercises:
 4360: @c 1. take inches and convert to feet and inches.
 4361: @c 2. take temperature and convert from fahrenheight to celcius;
 4362: @c    may need to care about symmetric vs floored??
 4363: @c 3. take input line and do character substitution
 4364: @c    to encipher or decipher
 4365: @c 4. as above but work on a file for in and out
 4366: @c 5. take input line and convert to pig-latin 
 4367: @c
 4368: @c thing of sets of things to exercise then come up with
 4369: @c problems that need those things.
 4370: 
 4371: 
 4372: @c ******************************************************************
 4373: @node Words, Error messages, Introduction, Top
 4374: @chapter Forth Words
 4375: @cindex words
 4376: 
 4377: @menu
 4378: * Notation::                    
 4379: * Case insensitivity::          
 4380: * Comments::                    
 4381: * Boolean Flags::               
 4382: * Arithmetic::                  
 4383: * Stack Manipulation::          
 4384: * Memory::                      
 4385: * Control Structures::          
 4386: * Defining Words::              
 4387: * Interpretation and Compilation Semantics::  
 4388: * Tokens for Words::            
 4389: * Compiling words::             
 4390: * The Text Interpreter::        
 4391: * The Input Stream::            
 4392: * Word Lists::                  
 4393: * Environmental Queries::       
 4394: * Files::                       
 4395: * Blocks::                      
 4396: * Other I/O::                   
 4397: * OS command line arguments::   
 4398: * Locals::                      
 4399: * Structures::                  
 4400: * Object-oriented Forth::       
 4401: * Programming Tools::           
 4402: * C Interface::                 
 4403: * Assembler and Code Words::    
 4404: * Threading Words::             
 4405: * Passing Commands to the OS::  
 4406: * Keeping track of Time::       
 4407: * Miscellaneous Words::         
 4408: @end menu
 4409: 
 4410: @node Notation, Case insensitivity, Words, Words
 4411: @section Notation
 4412: @cindex notation of glossary entries
 4413: @cindex format of glossary entries
 4414: @cindex glossary notation format
 4415: @cindex word glossary entry format
 4416: 
 4417: The Forth words are described in this section in the glossary notation
 4418: that has become a de-facto standard for Forth texts:
 4419: 
 4420: @format
 4421: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4422: @end format
 4423: @i{Description}
 4424: 
 4425: @table @var
 4426: @item word
 4427: The name of the word.
 4428: 
 4429: @item Stack effect
 4430: @cindex stack effect
 4431: The stack effect is written in the notation @code{@i{before} --
 4432: @i{after}}, where @i{before} and @i{after} describe the top of
 4433: stack entries before and after the execution of the word. The rest of
 4434: the stack is not touched by the word. The top of stack is rightmost,
 4435: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4436: uses a separate floating point stack, but a unified stack
 4437: notation. Also, return stack effects are not shown in @i{stack
 4438: effect}, but in @i{Description}. The name of a stack item describes
 4439: the type and/or the function of the item. See below for a discussion of
 4440: the types.
 4441: 
 4442: All words have two stack effects: A compile-time stack effect and a
 4443: run-time stack effect. The compile-time stack-effect of most words is
 4444: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4445: this standard behaviour, or the word does other unusual things at
 4446: compile time, both stack effects are shown; otherwise only the run-time
 4447: stack effect is shown.
 4448: 
 4449: Also note that in code templates or examples there can be comments in
 4450: parentheses that display the stack picture at this point; there is no
 4451: @code{--} in these places, because there is no before-after situation.
 4452: 
 4453: @cindex pronounciation of words
 4454: @item pronunciation
 4455: How the word is pronounced.
 4456: 
 4457: @cindex wordset
 4458: @cindex environment wordset
 4459: @item wordset
 4460: The ANS Forth standard is divided into several word sets. A standard
 4461: system need not support all of them. Therefore, in theory, the fewer
 4462: word sets your program uses the more portable it will be. However, we
 4463: suspect that most ANS Forth systems on personal machines will feature
 4464: all word sets. Words that are not defined in ANS Forth have
 4465: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4466: describes words that will work in future releases of Gforth;
 4467: @code{gforth-internal} words are more volatile. Environmental query
 4468: strings are also displayed like words; you can recognize them by the
 4469: @code{environment} in the word set field.
 4470: 
 4471: @item Description
 4472: A description of the behaviour of the word.
 4473: @end table
 4474: 
 4475: @cindex types of stack items
 4476: @cindex stack item types
 4477: The type of a stack item is specified by the character(s) the name
 4478: starts with:
 4479: 
 4480: @table @code
 4481: @item f
 4482: @cindex @code{f}, stack item type
 4483: Boolean flags, i.e. @code{false} or @code{true}.
 4484: @item c
 4485: @cindex @code{c}, stack item type
 4486: Char
 4487: @item w
 4488: @cindex @code{w}, stack item type
 4489: Cell, can contain an integer or an address
 4490: @item n
 4491: @cindex @code{n}, stack item type
 4492: signed integer
 4493: @item u
 4494: @cindex @code{u}, stack item type
 4495: unsigned integer
 4496: @item d
 4497: @cindex @code{d}, stack item type
 4498: double sized signed integer
 4499: @item ud
 4500: @cindex @code{ud}, stack item type
 4501: double sized unsigned integer
 4502: @item r
 4503: @cindex @code{r}, stack item type
 4504: Float (on the FP stack)
 4505: @item a-
 4506: @cindex @code{a_}, stack item type
 4507: Cell-aligned address
 4508: @item c-
 4509: @cindex @code{c_}, stack item type
 4510: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4511: @item f-
 4512: @cindex @code{f_}, stack item type
 4513: Float-aligned address
 4514: @item df-
 4515: @cindex @code{df_}, stack item type
 4516: Address aligned for IEEE double precision float
 4517: @item sf-
 4518: @cindex @code{sf_}, stack item type
 4519: Address aligned for IEEE single precision float
 4520: @item xt
 4521: @cindex @code{xt}, stack item type
 4522: Execution token, same size as Cell
 4523: @item wid
 4524: @cindex @code{wid}, stack item type
 4525: Word list ID, same size as Cell
 4526: @item ior, wior
 4527: @cindex ior type description
 4528: @cindex wior type description
 4529: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4530: @item f83name
 4531: @cindex @code{f83name}, stack item type
 4532: Pointer to a name structure
 4533: @item "
 4534: @cindex @code{"}, stack item type
 4535: string in the input stream (not on the stack). The terminating character
 4536: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4537: quotes.
 4538: @end table
 4539: 
 4540: @comment ----------------------------------------------
 4541: @node Case insensitivity, Comments, Notation, Words
 4542: @section Case insensitivity
 4543: @cindex case sensitivity
 4544: @cindex upper and lower case
 4545: 
 4546: Gforth is case-insensitive; you can enter definitions and invoke
 4547: Standard words using upper, lower or mixed case (however,
 4548: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4549: options}).
 4550: 
 4551: ANS Forth only @i{requires} implementations to recognise Standard words
 4552: when they are typed entirely in upper case. Therefore, a Standard
 4553: program must use upper case for all Standard words. You can use whatever
 4554: case you like for words that you define, but in a Standard program you
 4555: have to use the words in the same case that you defined them.
 4556: 
 4557: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4558: wordlists, @pxref{Word Lists}).
 4559: 
 4560: Two people have asked how to convert Gforth to be case-sensitive; while
 4561: we think this is a bad idea, you can change all wordlists into tables
 4562: like this:
 4563: 
 4564: @example
 4565: ' table-find forth-wordlist wordlist-map @ !
 4566: @end example
 4567: 
 4568: Note that you now have to type the predefined words in the same case
 4569: that we defined them, which are varying.  You may want to convert them
 4570: to your favourite case before doing this operation (I won't explain how,
 4571: because if you are even contemplating doing this, you'd better have
 4572: enough knowledge of Forth systems to know this already).
 4573: 
 4574: @node Comments, Boolean Flags, Case insensitivity, Words
 4575: @section Comments
 4576: @cindex comments
 4577: 
 4578: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4579: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4580: 
 4581: 
 4582: doc-(
 4583: doc-\
 4584: doc-\G
 4585: 
 4586: 
 4587: @node Boolean Flags, Arithmetic, Comments, Words
 4588: @section Boolean Flags
 4589: @cindex Boolean flags
 4590: 
 4591: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4592: flag @code{false} and a flag with all bits set represents the flag
 4593: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4594: a cell that has @i{any} bit set as @code{true}.
 4595: @c on and off to Memory? 
 4596: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4597: 
 4598: doc-true
 4599: doc-false
 4600: doc-on
 4601: doc-off
 4602: 
 4603: 
 4604: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4605: @section Arithmetic
 4606: @cindex arithmetic words
 4607: 
 4608: @cindex division with potentially negative operands
 4609: Forth arithmetic is not checked, i.e., you will not hear about integer
 4610: overflow on addition or multiplication, you may hear about division by
 4611: zero if you are lucky. The operator is written after the operands, but
 4612: the operands are still in the original order. I.e., the infix @code{2-1}
 4613: corresponds to @code{2 1 -}. Forth offers a variety of division
 4614: operators. If you perform division with potentially negative operands,
 4615: you do not want to use @code{/} or @code{/mod} with its undefined
 4616: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4617: former, @pxref{Mixed precision}).
 4618: @comment TODO discuss the different division forms and the std approach
 4619: 
 4620: @menu
 4621: * Single precision::            
 4622: * Double precision::            Double-cell integer arithmetic
 4623: * Bitwise operations::          
 4624: * Numeric comparison::          
 4625: * Mixed precision::             Operations with single and double-cell integers
 4626: * Floating Point::              
 4627: @end menu
 4628: 
 4629: @node Single precision, Double precision, Arithmetic, Arithmetic
 4630: @subsection Single precision
 4631: @cindex single precision arithmetic words
 4632: 
 4633: @c !! cell undefined
 4634: 
 4635: By default, numbers in Forth are single-precision integers that are one
 4636: cell in size. They can be signed or unsigned, depending upon how you
 4637: treat them. For the rules used by the text interpreter for recognising
 4638: single-precision integers see @ref{Number Conversion}.
 4639: 
 4640: These words are all defined for signed operands, but some of them also
 4641: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4642: @code{*}.
 4643: 
 4644: doc-+
 4645: doc-1+
 4646: doc-under+
 4647: doc--
 4648: doc-1-
 4649: doc-*
 4650: doc-/
 4651: doc-mod
 4652: doc-/mod
 4653: doc-negate
 4654: doc-abs
 4655: doc-min
 4656: doc-max
 4657: doc-floored
 4658: 
 4659: 
 4660: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4661: @subsection Double precision
 4662: @cindex double precision arithmetic words
 4663: 
 4664: For the rules used by the text interpreter for
 4665: recognising double-precision integers, see @ref{Number Conversion}.
 4666: 
 4667: A double precision number is represented by a cell pair, with the most
 4668: significant cell at the TOS. It is trivial to convert an unsigned single
 4669: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4670: represented by Gforth using 2's complement arithmetic, converting a
 4671: signed single to a (signed) double requires sign-extension across the
 4672: most significant cell. This can be achieved using @code{s>d}. The moral
 4673: of the story is that you cannot convert a number without knowing whether
 4674: it represents an unsigned or a signed number.
 4675: 
 4676: These words are all defined for signed operands, but some of them also
 4677: work for unsigned numbers: @code{d+}, @code{d-}.
 4678: 
 4679: doc-s>d
 4680: doc-d>s
 4681: doc-d+
 4682: doc-d-
 4683: doc-dnegate
 4684: doc-dabs
 4685: doc-dmin
 4686: doc-dmax
 4687: 
 4688: 
 4689: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4690: @subsection Bitwise operations
 4691: @cindex bitwise operation words
 4692: 
 4693: 
 4694: doc-and
 4695: doc-or
 4696: doc-xor
 4697: doc-invert
 4698: doc-lshift
 4699: doc-rshift
 4700: doc-2*
 4701: doc-d2*
 4702: doc-2/
 4703: doc-d2/
 4704: 
 4705: 
 4706: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4707: @subsection Numeric comparison
 4708: @cindex numeric comparison words
 4709: 
 4710: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4711: d0= d0<>}) work for for both signed and unsigned numbers.
 4712: 
 4713: doc-<
 4714: doc-<=
 4715: doc-<>
 4716: doc-=
 4717: doc->
 4718: doc->=
 4719: 
 4720: doc-0<
 4721: doc-0<=
 4722: doc-0<>
 4723: doc-0=
 4724: doc-0>
 4725: doc-0>=
 4726: 
 4727: doc-u<
 4728: doc-u<=
 4729: @c u<> and u= exist but are the same as <> and =
 4730: @c doc-u<>
 4731: @c doc-u=
 4732: doc-u>
 4733: doc-u>=
 4734: 
 4735: doc-within
 4736: 
 4737: doc-d<
 4738: doc-d<=
 4739: doc-d<>
 4740: doc-d=
 4741: doc-d>
 4742: doc-d>=
 4743: 
 4744: doc-d0<
 4745: doc-d0<=
 4746: doc-d0<>
 4747: doc-d0=
 4748: doc-d0>
 4749: doc-d0>=
 4750: 
 4751: doc-du<
 4752: doc-du<=
 4753: @c du<> and du= exist but are the same as d<> and d=
 4754: @c doc-du<>
 4755: @c doc-du=
 4756: doc-du>
 4757: doc-du>=
 4758: 
 4759: 
 4760: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4761: @subsection Mixed precision
 4762: @cindex mixed precision arithmetic words
 4763: 
 4764: 
 4765: doc-m+
 4766: doc-*/
 4767: doc-*/mod
 4768: doc-m*
 4769: doc-um*
 4770: doc-m*/
 4771: doc-um/mod
 4772: doc-fm/mod
 4773: doc-sm/rem
 4774: 
 4775: 
 4776: @node Floating Point,  , Mixed precision, Arithmetic
 4777: @subsection Floating Point
 4778: @cindex floating point arithmetic words
 4779: 
 4780: For the rules used by the text interpreter for
 4781: recognising floating-point numbers see @ref{Number Conversion}.
 4782: 
 4783: Gforth has a separate floating point stack, but the documentation uses
 4784: the unified notation.@footnote{It's easy to generate the separate
 4785: notation from that by just separating the floating-point numbers out:
 4786: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4787: r3 )}.}
 4788: 
 4789: @cindex floating-point arithmetic, pitfalls
 4790: Floating point numbers have a number of unpleasant surprises for the
 4791: unwary (e.g., floating point addition is not associative) and even a
 4792: few for the wary. You should not use them unless you know what you are
 4793: doing or you don't care that the results you get are totally bogus. If
 4794: you want to learn about the problems of floating point numbers (and
 4795: how to avoid them), you might start with @cite{David Goldberg,
 4796: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 4797: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 4798: Computing Surveys 23(1):5@minus{}48, March 1991}.
 4799: 
 4800: 
 4801: doc-d>f
 4802: doc-f>d
 4803: doc-f+
 4804: doc-f-
 4805: doc-f*
 4806: doc-f/
 4807: doc-fnegate
 4808: doc-fabs
 4809: doc-fmax
 4810: doc-fmin
 4811: doc-floor
 4812: doc-fround
 4813: doc-f**
 4814: doc-fsqrt
 4815: doc-fexp
 4816: doc-fexpm1
 4817: doc-fln
 4818: doc-flnp1
 4819: doc-flog
 4820: doc-falog
 4821: doc-f2*
 4822: doc-f2/
 4823: doc-1/f
 4824: doc-precision
 4825: doc-set-precision
 4826: 
 4827: @cindex angles in trigonometric operations
 4828: @cindex trigonometric operations
 4829: Angles in floating point operations are given in radians (a full circle
 4830: has 2 pi radians).
 4831: 
 4832: doc-fsin
 4833: doc-fcos
 4834: doc-fsincos
 4835: doc-ftan
 4836: doc-fasin
 4837: doc-facos
 4838: doc-fatan
 4839: doc-fatan2
 4840: doc-fsinh
 4841: doc-fcosh
 4842: doc-ftanh
 4843: doc-fasinh
 4844: doc-facosh
 4845: doc-fatanh
 4846: doc-pi
 4847: 
 4848: @cindex equality of floats
 4849: @cindex floating-point comparisons
 4850: One particular problem with floating-point arithmetic is that comparison
 4851: for equality often fails when you would expect it to succeed.  For this
 4852: reason approximate equality is often preferred (but you still have to
 4853: know what you are doing).  Also note that IEEE NaNs may compare
 4854: differently from what you might expect.  The comparison words are:
 4855: 
 4856: doc-f~rel
 4857: doc-f~abs
 4858: doc-f~
 4859: doc-f=
 4860: doc-f<>
 4861: 
 4862: doc-f<
 4863: doc-f<=
 4864: doc-f>
 4865: doc-f>=
 4866: 
 4867: doc-f0<
 4868: doc-f0<=
 4869: doc-f0<>
 4870: doc-f0=
 4871: doc-f0>
 4872: doc-f0>=
 4873: 
 4874: 
 4875: @node Stack Manipulation, Memory, Arithmetic, Words
 4876: @section Stack Manipulation
 4877: @cindex stack manipulation words
 4878: 
 4879: @cindex floating-point stack in the standard
 4880: Gforth maintains a number of separate stacks:
 4881: 
 4882: @cindex data stack
 4883: @cindex parameter stack
 4884: @itemize @bullet
 4885: @item
 4886: A data stack (also known as the @dfn{parameter stack}) -- for
 4887: characters, cells, addresses, and double cells.
 4888: 
 4889: @cindex floating-point stack
 4890: @item
 4891: A floating point stack -- for holding floating point (FP) numbers.
 4892: 
 4893: @cindex return stack
 4894: @item
 4895: A return stack -- for holding the return addresses of colon
 4896: definitions and other (non-FP) data.
 4897: 
 4898: @cindex locals stack
 4899: @item
 4900: A locals stack -- for holding local variables.
 4901: @end itemize
 4902: 
 4903: @menu
 4904: * Data stack::                  
 4905: * Floating point stack::        
 4906: * Return stack::                
 4907: * Locals stack::                
 4908: * Stack pointer manipulation::  
 4909: @end menu
 4910: 
 4911: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4912: @subsection Data stack
 4913: @cindex data stack manipulation words
 4914: @cindex stack manipulations words, data stack
 4915: 
 4916: 
 4917: doc-drop
 4918: doc-nip
 4919: doc-dup
 4920: doc-over
 4921: doc-tuck
 4922: doc-swap
 4923: doc-pick
 4924: doc-rot
 4925: doc--rot
 4926: doc-?dup
 4927: doc-roll
 4928: doc-2drop
 4929: doc-2nip
 4930: doc-2dup
 4931: doc-2over
 4932: doc-2tuck
 4933: doc-2swap
 4934: doc-2rot
 4935: 
 4936: 
 4937: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4938: @subsection Floating point stack
 4939: @cindex floating-point stack manipulation words
 4940: @cindex stack manipulation words, floating-point stack
 4941: 
 4942: Whilst every sane Forth has a separate floating-point stack, it is not
 4943: strictly required; an ANS Forth system could theoretically keep
 4944: floating-point numbers on the data stack. As an additional difficulty,
 4945: you don't know how many cells a floating-point number takes. It is
 4946: reportedly possible to write words in a way that they work also for a
 4947: unified stack model, but we do not recommend trying it. Instead, just
 4948: say that your program has an environmental dependency on a separate
 4949: floating-point stack.
 4950: 
 4951: doc-floating-stack
 4952: 
 4953: doc-fdrop
 4954: doc-fnip
 4955: doc-fdup
 4956: doc-fover
 4957: doc-ftuck
 4958: doc-fswap
 4959: doc-fpick
 4960: doc-frot
 4961: 
 4962: 
 4963: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4964: @subsection Return stack
 4965: @cindex return stack manipulation words
 4966: @cindex stack manipulation words, return stack
 4967: 
 4968: @cindex return stack and locals
 4969: @cindex locals and return stack
 4970: A Forth system is allowed to keep local variables on the
 4971: return stack. This is reasonable, as local variables usually eliminate
 4972: the need to use the return stack explicitly. So, if you want to produce
 4973: a standard compliant program and you are using local variables in a
 4974: word, forget about return stack manipulations in that word (refer to the
 4975: standard document for the exact rules).
 4976: 
 4977: doc->r
 4978: doc-r>
 4979: doc-r@
 4980: doc-rdrop
 4981: doc-2>r
 4982: doc-2r>
 4983: doc-2r@
 4984: doc-2rdrop
 4985: 
 4986: 
 4987: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4988: @subsection Locals stack
 4989: 
 4990: Gforth uses an extra locals stack.  It is described, along with the
 4991: reasons for its existence, in @ref{Locals implementation}.
 4992: 
 4993: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4994: @subsection Stack pointer manipulation
 4995: @cindex stack pointer manipulation words
 4996: 
 4997: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4998: doc-sp0
 4999: doc-sp@
 5000: doc-sp!
 5001: doc-fp0
 5002: doc-fp@
 5003: doc-fp!
 5004: doc-rp0
 5005: doc-rp@
 5006: doc-rp!
 5007: doc-lp0
 5008: doc-lp@
 5009: doc-lp!
 5010: 
 5011: 
 5012: @node Memory, Control Structures, Stack Manipulation, Words
 5013: @section Memory
 5014: @cindex memory words
 5015: 
 5016: @menu
 5017: * Memory model::                
 5018: * Dictionary allocation::       
 5019: * Heap Allocation::             
 5020: * Memory Access::               
 5021: * Address arithmetic::          
 5022: * Memory Blocks::               
 5023: @end menu
 5024: 
 5025: In addition to the standard Forth memory allocation words, there is also
 5026: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 5027: garbage collector}.
 5028: 
 5029: @node Memory model, Dictionary allocation, Memory, Memory
 5030: @subsection ANS Forth and Gforth memory models
 5031: 
 5032: @c The ANS Forth description is a mess (e.g., is the heap part of
 5033: @c the dictionary?), so let's not stick to closely with it.
 5034: 
 5035: ANS Forth considers a Forth system as consisting of several address
 5036: spaces, of which only @dfn{data space} is managed and accessible with
 5037: the memory words.  Memory not necessarily in data space includes the
 5038: stacks, the code (called code space) and the headers (called name
 5039: space). In Gforth everything is in data space, but the code for the
 5040: primitives is usually read-only.
 5041: 
 5042: Data space is divided into a number of areas: The (data space portion of
 5043: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 5044: refer to the search data structure embodied in word lists and headers,
 5045: because it is used for looking up names, just as you would in a
 5046: conventional dictionary.}, the heap, and a number of system-allocated
 5047: buffers.
 5048: 
 5049: @cindex address arithmetic restrictions, ANS vs. Gforth
 5050: @cindex contiguous regions, ANS vs. Gforth
 5051: In ANS Forth data space is also divided into contiguous regions.  You
 5052: can only use address arithmetic within a contiguous region, not between
 5053: them.  Usually each allocation gives you one contiguous region, but the
 5054: dictionary allocation words have additional rules (@pxref{Dictionary
 5055: allocation}).
 5056: 
 5057: Gforth provides one big address space, and address arithmetic can be
 5058: performed between any addresses. However, in the dictionary headers or
 5059: code are interleaved with data, so almost the only contiguous data space
 5060: regions there are those described by ANS Forth as contiguous; but you
 5061: can be sure that the dictionary is allocated towards increasing
 5062: addresses even between contiguous regions.  The memory order of
 5063: allocations in the heap is platform-dependent (and possibly different
 5064: from one run to the next).
 5065: 
 5066: 
 5067: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 5068: @subsection Dictionary allocation
 5069: @cindex reserving data space
 5070: @cindex data space - reserving some
 5071: 
 5072: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 5073: you want to deallocate X, you also deallocate everything
 5074: allocated after X.
 5075: 
 5076: @cindex contiguous regions in dictionary allocation
 5077: The allocations using the words below are contiguous and grow the region
 5078: towards increasing addresses.  Other words that allocate dictionary
 5079: memory of any kind (i.e., defining words including @code{:noname}) end
 5080: the contiguous region and start a new one.
 5081: 
 5082: In ANS Forth only @code{create}d words are guaranteed to produce an
 5083: address that is the start of the following contiguous region.  In
 5084: particular, the cell allocated by @code{variable} is not guaranteed to
 5085: be contiguous with following @code{allot}ed memory.
 5086: 
 5087: You can deallocate memory by using @code{allot} with a negative argument
 5088: (with some restrictions, see @code{allot}). For larger deallocations use
 5089: @code{marker}.
 5090: 
 5091: 
 5092: doc-here
 5093: doc-unused
 5094: doc-allot
 5095: doc-c,
 5096: doc-f,
 5097: doc-,
 5098: doc-2,
 5099: 
 5100: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 5101: course you should allocate memory in an aligned way, too. I.e., before
 5102: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 5103: The words below align @code{here} if it is not already.  Basically it is
 5104: only already aligned for a type, if the last allocation was a multiple
 5105: of the size of this type and if @code{here} was aligned for this type
 5106: before.
 5107: 
 5108: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 5109: ANS Forth (@code{maxalign}ed in Gforth).
 5110: 
 5111: doc-align
 5112: doc-falign
 5113: doc-sfalign
 5114: doc-dfalign
 5115: doc-maxalign
 5116: doc-cfalign
 5117: 
 5118: 
 5119: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 5120: @subsection Heap allocation
 5121: @cindex heap allocation
 5122: @cindex dynamic allocation of memory
 5123: @cindex memory-allocation word set
 5124: 
 5125: @cindex contiguous regions and heap allocation
 5126: Heap allocation supports deallocation of allocated memory in any
 5127: order. Dictionary allocation is not affected by it (i.e., it does not
 5128: end a contiguous region). In Gforth, these words are implemented using
 5129: the standard C library calls malloc(), free() and resize().
 5130: 
 5131: The memory region produced by one invocation of @code{allocate} or
 5132: @code{resize} is internally contiguous.  There is no contiguity between
 5133: such a region and any other region (including others allocated from the
 5134: heap).
 5135: 
 5136: doc-allocate
 5137: doc-free
 5138: doc-resize
 5139: 
 5140: 
 5141: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5142: @subsection Memory Access
 5143: @cindex memory access words
 5144: 
 5145: doc-@
 5146: doc-!
 5147: doc-+!
 5148: doc-c@
 5149: doc-c!
 5150: doc-2@
 5151: doc-2!
 5152: doc-f@
 5153: doc-f!
 5154: doc-sf@
 5155: doc-sf!
 5156: doc-df@
 5157: doc-df!
 5158: doc-sw@
 5159: doc-uw@
 5160: doc-w!
 5161: doc-sl@
 5162: doc-ul@
 5163: doc-l!
 5164: 
 5165: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5166: @subsection Address arithmetic
 5167: @cindex address arithmetic words
 5168: 
 5169: Address arithmetic is the foundation on which you can build data
 5170: structures like arrays, records (@pxref{Structures}) and objects
 5171: (@pxref{Object-oriented Forth}).
 5172: 
 5173: @cindex address unit
 5174: @cindex au (address unit)
 5175: ANS Forth does not specify the sizes of the data types. Instead, it
 5176: offers a number of words for computing sizes and doing address
 5177: arithmetic. Address arithmetic is performed in terms of address units
 5178: (aus); on most systems the address unit is one byte. Note that a
 5179: character may have more than one au, so @code{chars} is no noop (on
 5180: platforms where it is a noop, it compiles to nothing).
 5181: 
 5182: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5183: you have the address of a cell, perform @code{1 cells +}, and you will
 5184: have the address of the next cell.
 5185: 
 5186: @cindex contiguous regions and address arithmetic
 5187: In ANS Forth you can perform address arithmetic only within a contiguous
 5188: region, i.e., if you have an address into one region, you can only add
 5189: and subtract such that the result is still within the region; you can
 5190: only subtract or compare addresses from within the same contiguous
 5191: region.  Reasons: several contiguous regions can be arranged in memory
 5192: in any way; on segmented systems addresses may have unusual
 5193: representations, such that address arithmetic only works within a
 5194: region.  Gforth provides a few more guarantees (linear address space,
 5195: dictionary grows upwards), but in general I have found it easy to stay
 5196: within contiguous regions (exception: computing and comparing to the
 5197: address just beyond the end of an array).
 5198: 
 5199: @cindex alignment of addresses for types
 5200: ANS Forth also defines words for aligning addresses for specific
 5201: types. Many computers require that accesses to specific data types
 5202: must only occur at specific addresses; e.g., that cells may only be
 5203: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5204: accesses, it can usually perform aligned accesses faster. 
 5205: 
 5206: For the performance-conscious: alignment operations are usually only
 5207: necessary during the definition of a data structure, not during the
 5208: (more frequent) accesses to it.
 5209: 
 5210: ANS Forth defines no words for character-aligning addresses. This is not
 5211: an oversight, but reflects the fact that addresses that are not
 5212: char-aligned have no use in the standard and therefore will not be
 5213: created.
 5214: 
 5215: @cindex @code{CREATE} and alignment
 5216: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5217: are cell-aligned; in addition, Gforth guarantees that these addresses
 5218: are aligned for all purposes.
 5219: 
 5220: Note that the ANS Forth word @code{char} has nothing to do with address
 5221: arithmetic.
 5222: 
 5223: 
 5224: doc-chars
 5225: doc-char+
 5226: doc-cells
 5227: doc-cell+
 5228: doc-cell
 5229: doc-aligned
 5230: doc-floats
 5231: doc-float+
 5232: doc-float
 5233: doc-faligned
 5234: doc-sfloats
 5235: doc-sfloat+
 5236: doc-sfaligned
 5237: doc-dfloats
 5238: doc-dfloat+
 5239: doc-dfaligned
 5240: doc-maxaligned
 5241: doc-cfaligned
 5242: doc-address-unit-bits
 5243: doc-/w
 5244: doc-/l
 5245: 
 5246: @node Memory Blocks,  , Address arithmetic, Memory
 5247: @subsection Memory Blocks
 5248: @cindex memory block words
 5249: @cindex character strings - moving and copying
 5250: 
 5251: Memory blocks often represent character strings; For ways of storing
 5252: character strings in memory see @ref{String Formats}.  For other
 5253: string-processing words see @ref{Displaying characters and strings}.
 5254: 
 5255: A few of these words work on address unit blocks.  In that case, you
 5256: usually have to insert @code{CHARS} before the word when working on
 5257: character strings.  Most words work on character blocks, and expect a
 5258: char-aligned address.
 5259: 
 5260: When copying characters between overlapping memory regions, use
 5261: @code{chars move} or choose carefully between @code{cmove} and
 5262: @code{cmove>}.
 5263: 
 5264: doc-move
 5265: doc-erase
 5266: doc-cmove
 5267: doc-cmove>
 5268: doc-fill
 5269: doc-blank
 5270: doc-compare
 5271: doc-str=
 5272: doc-str<
 5273: doc-string-prefix?
 5274: doc-search
 5275: doc--trailing
 5276: doc-/string
 5277: doc-bounds
 5278: doc-pad
 5279: 
 5280: @comment TODO examples
 5281: 
 5282: 
 5283: @node Control Structures, Defining Words, Memory, Words
 5284: @section Control Structures
 5285: @cindex control structures
 5286: 
 5287: Control structures in Forth cannot be used interpretively, only in a
 5288: colon definition@footnote{To be precise, they have no interpretation
 5289: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5290: not like this limitation, but have not seen a satisfying way around it
 5291: yet, although many schemes have been proposed.
 5292: 
 5293: @menu
 5294: * Selection::                   IF ... ELSE ... ENDIF
 5295: * Simple Loops::                BEGIN ...
 5296: * Counted Loops::               DO
 5297: * Arbitrary control structures::  
 5298: * Calls and returns::           
 5299: * Exception Handling::          
 5300: @end menu
 5301: 
 5302: @node Selection, Simple Loops, Control Structures, Control Structures
 5303: @subsection Selection
 5304: @cindex selection control structures
 5305: @cindex control structures for selection
 5306: 
 5307: @cindex @code{IF} control structure
 5308: @example
 5309: @i{flag}
 5310: IF
 5311:   @i{code}
 5312: ENDIF
 5313: @end example
 5314: @noindent
 5315: 
 5316: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5317: with any bit set represents truth) @i{code} is executed.
 5318: 
 5319: @example
 5320: @i{flag}
 5321: IF
 5322:   @i{code1}
 5323: ELSE
 5324:   @i{code2}
 5325: ENDIF
 5326: @end example
 5327: 
 5328: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5329: executed.
 5330: 
 5331: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5332: standard, and @code{ENDIF} is not, although it is quite popular. We
 5333: recommend using @code{ENDIF}, because it is less confusing for people
 5334: who also know other languages (and is not prone to reinforcing negative
 5335: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5336: system that only supplies @code{THEN} is simple:
 5337: @example
 5338: : ENDIF   POSTPONE then ; immediate
 5339: @end example
 5340: 
 5341: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5342: (adv.)}  has the following meanings:
 5343: @quotation
 5344: ... 2b: following next after in order ... 3d: as a necessary consequence
 5345: (if you were there, then you saw them).
 5346: @end quotation
 5347: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5348: and many other programming languages has the meaning 3d.]
 5349: 
 5350: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5351: you can avoid using @code{?dup}. Using these alternatives is also more
 5352: efficient than using @code{?dup}. Definitions in ANS Forth
 5353: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5354: @file{compat/control.fs}.
 5355: 
 5356: @cindex @code{CASE} control structure
 5357: @example
 5358: @i{x}
 5359: CASE
 5360:   @i{x1} OF @i{code1} ENDOF
 5361:   @i{x2} OF @i{code2} ENDOF
 5362:   @dots{}
 5363:   ( x ) @i{default-code} ( x )
 5364: ENDCASE ( )
 5365: @end example
 5366: 
 5367: Executes the first @i{codei}, where the @i{xi} is equal to @i{x}.  If no
 5368: @i{xi} matches, the optional @i{default-code} is executed. The optional
 5369: default case can be added by simply writing the code after the last
 5370: @code{ENDOF}. It may use @i{x}, which is on top of the stack, but must
 5371: not consume it.  The value @i{x} is consumed by this construction
 5372: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
 5373: matches).  Example:
 5374: 
 5375: @example
 5376: : num-name ( n -- c-addr u )
 5377:  case
 5378:    0 of s" zero " endof
 5379:    1 of s" one "  endof
 5380:    2 of s" two "  endof
 5381:    \ default case:
 5382:    s" other number" 
 5383:    rot \ get n on top so ENDCASE can drop it
 5384:  endcase ;
 5385: @end example
 5386: 
 5387: @progstyle
 5388: To keep the code understandable, you should ensure that you change the
 5389: stack in the same way (wrt. number and types of stack items consumed
 5390: and pushed) on all paths through a selection construct.
 5391: 
 5392: @node Simple Loops, Counted Loops, Selection, Control Structures
 5393: @subsection Simple Loops
 5394: @cindex simple loops
 5395: @cindex loops without count 
 5396: 
 5397: @cindex @code{WHILE} loop
 5398: @example
 5399: BEGIN
 5400:   @i{code1}
 5401:   @i{flag}
 5402: WHILE
 5403:   @i{code2}
 5404: REPEAT
 5405: @end example
 5406: 
 5407: @i{code1} is executed and @i{flag} is computed. If it is true,
 5408: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5409: false, execution continues after the @code{REPEAT}.
 5410: 
 5411: @cindex @code{UNTIL} loop
 5412: @example
 5413: BEGIN
 5414:   @i{code}
 5415:   @i{flag}
 5416: UNTIL
 5417: @end example
 5418: 
 5419: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5420: 
 5421: @progstyle
 5422: To keep the code understandable, a complete iteration of the loop should
 5423: not change the number and types of the items on the stacks.
 5424: 
 5425: @cindex endless loop
 5426: @cindex loops, endless
 5427: @example
 5428: BEGIN
 5429:   @i{code}
 5430: AGAIN
 5431: @end example
 5432: 
 5433: This is an endless loop.
 5434: 
 5435: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5436: @subsection Counted Loops
 5437: @cindex counted loops
 5438: @cindex loops, counted
 5439: @cindex @code{DO} loops
 5440: 
 5441: The basic counted loop is:
 5442: @example
 5443: @i{limit} @i{start}
 5444: ?DO
 5445:   @i{body}
 5446: LOOP
 5447: @end example
 5448: 
 5449: This performs one iteration for every integer, starting from @i{start}
 5450: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5451: accessed with @code{i}. For example, the loop:
 5452: @example
 5453: 10 0 ?DO
 5454:   i .
 5455: LOOP
 5456: @end example
 5457: @noindent
 5458: prints @code{0 1 2 3 4 5 6 7 8 9}
 5459: 
 5460: The index of the innermost loop can be accessed with @code{i}, the index
 5461: of the next loop with @code{j}, and the index of the third loop with
 5462: @code{k}.
 5463: 
 5464: 
 5465: doc-i
 5466: doc-j
 5467: doc-k
 5468: 
 5469: 
 5470: The loop control data are kept on the return stack, so there are some
 5471: restrictions on mixing return stack accesses and counted loop words. In
 5472: particuler, if you put values on the return stack outside the loop, you
 5473: cannot read them inside the loop@footnote{well, not in a way that is
 5474: portable.}. If you put values on the return stack within a loop, you
 5475: have to remove them before the end of the loop and before accessing the
 5476: index of the loop.
 5477: 
 5478: There are several variations on the counted loop:
 5479: 
 5480: @itemize @bullet
 5481: @item
 5482: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5483: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5484: 
 5485: @example
 5486: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5487: @end example
 5488: prints @code{0 1 2 3}
 5489: 
 5490: 
 5491: @item
 5492: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5493: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5494: return stack so @code{EXIT} can get to its return address. For example:
 5495: 
 5496: @example
 5497: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5498: @end example
 5499: prints @code{0 1 2 3}
 5500: 
 5501: 
 5502: @item
 5503: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5504: (and @code{LOOP} iterates until they become equal by wrap-around
 5505: arithmetic). This behaviour is usually not what you want. Therefore,
 5506: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5507: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5508: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5509: unsigned loop parameters.
 5510: 
 5511: @item
 5512: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5513: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5514: if you know that the loop is entered in any case. Such knowledge tends
 5515: to become invalid during maintenance of a program, and then the
 5516: @code{DO} will make trouble.
 5517: 
 5518: @item
 5519: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5520: index by @i{n} instead of by 1. The loop is terminated when the border
 5521: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5522: 
 5523: @example
 5524: 4 0 +DO  i .  2 +LOOP
 5525: @end example
 5526: @noindent
 5527: prints @code{0 2}
 5528: 
 5529: @example
 5530: 4 1 +DO  i .  2 +LOOP
 5531: @end example
 5532: @noindent
 5533: prints @code{1 3}
 5534: 
 5535: @item
 5536: @cindex negative increment for counted loops
 5537: @cindex counted loops with negative increment
 5538: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5539: 
 5540: @example
 5541: -1 0 ?DO  i .  -1 +LOOP
 5542: @end example
 5543: @noindent
 5544: prints @code{0 -1}
 5545: 
 5546: @example
 5547: 0 0 ?DO  i .  -1 +LOOP
 5548: @end example
 5549: prints nothing.
 5550: 
 5551: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5552: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5553: index by @i{u} each iteration. The loop is terminated when the border
 5554: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5555: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5556: 
 5557: @example
 5558: -2 0 -DO  i .  1 -LOOP
 5559: @end example
 5560: @noindent
 5561: prints @code{0 -1}
 5562: 
 5563: @example
 5564: -1 0 -DO  i .  1 -LOOP
 5565: @end example
 5566: @noindent
 5567: prints @code{0}
 5568: 
 5569: @example
 5570: 0 0 -DO  i .  1 -LOOP
 5571: @end example
 5572: @noindent
 5573: prints nothing.
 5574: 
 5575: @end itemize
 5576: 
 5577: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5578: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5579: for these words that uses only standard words is provided in
 5580: @file{compat/loops.fs}.
 5581: 
 5582: 
 5583: @cindex @code{FOR} loops
 5584: Another counted loop is:
 5585: @example
 5586: @i{n}
 5587: FOR
 5588:   @i{body}
 5589: NEXT
 5590: @end example
 5591: This is the preferred loop of native code compiler writers who are too
 5592: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5593: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5594: @code{i} produces values starting with @i{n} and ending with 0. Other
 5595: Forth systems may behave differently, even if they support @code{FOR}
 5596: loops. To avoid problems, don't use @code{FOR} loops.
 5597: 
 5598: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5599: @subsection Arbitrary control structures
 5600: @cindex control structures, user-defined
 5601: 
 5602: @cindex control-flow stack
 5603: ANS Forth permits and supports using control structures in a non-nested
 5604: way. Information about incomplete control structures is stored on the
 5605: control-flow stack. This stack may be implemented on the Forth data
 5606: stack, and this is what we have done in Gforth.
 5607: 
 5608: @cindex @code{orig}, control-flow stack item
 5609: @cindex @code{dest}, control-flow stack item
 5610: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5611: entry represents a backward branch target. A few words are the basis for
 5612: building any control structure possible (except control structures that
 5613: need storage, like calls, coroutines, and backtracking).
 5614: 
 5615: 
 5616: doc-if
 5617: doc-ahead
 5618: doc-then
 5619: doc-begin
 5620: doc-until
 5621: doc-again
 5622: doc-cs-pick
 5623: doc-cs-roll
 5624: 
 5625: 
 5626: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5627: manipulate the control-flow stack in a portable way. Without them, you
 5628: would need to know how many stack items are occupied by a control-flow
 5629: entry (many systems use one cell. In Gforth they currently take three,
 5630: but this may change in the future).
 5631: 
 5632: Some standard control structure words are built from these words:
 5633: 
 5634: 
 5635: doc-else
 5636: doc-while
 5637: doc-repeat
 5638: 
 5639: 
 5640: @noindent
 5641: Gforth adds some more control-structure words:
 5642: 
 5643: 
 5644: doc-endif
 5645: doc-?dup-if
 5646: doc-?dup-0=-if
 5647: 
 5648: 
 5649: @noindent
 5650: Counted loop words constitute a separate group of words:
 5651: 
 5652: 
 5653: doc-?do
 5654: doc-+do
 5655: doc-u+do
 5656: doc--do
 5657: doc-u-do
 5658: doc-do
 5659: doc-for
 5660: doc-loop
 5661: doc-+loop
 5662: doc--loop
 5663: doc-next
 5664: doc-leave
 5665: doc-?leave
 5666: doc-unloop
 5667: doc-done
 5668: 
 5669: 
 5670: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5671: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5672: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5673: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5674: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5675: resolved (by using one of the loop-ending words or @code{DONE}).
 5676: 
 5677: @noindent
 5678: Another group of control structure words are:
 5679: 
 5680: 
 5681: doc-case
 5682: doc-endcase
 5683: doc-of
 5684: doc-endof
 5685: 
 5686: 
 5687: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5688: @code{CS-ROLL}.
 5689: 
 5690: @subsubsection Programming Style
 5691: @cindex control structures programming style
 5692: @cindex programming style, arbitrary control structures
 5693: 
 5694: In order to ensure readability we recommend that you do not create
 5695: arbitrary control structures directly, but define new control structure
 5696: words for the control structure you want and use these words in your
 5697: program. For example, instead of writing:
 5698: 
 5699: @example
 5700: BEGIN
 5701:   ...
 5702: IF [ 1 CS-ROLL ]
 5703:   ...
 5704: AGAIN THEN
 5705: @end example
 5706: 
 5707: @noindent
 5708: we recommend defining control structure words, e.g.,
 5709: 
 5710: @example
 5711: : WHILE ( DEST -- ORIG DEST )
 5712:  POSTPONE IF
 5713:  1 CS-ROLL ; immediate
 5714: 
 5715: : REPEAT ( orig dest -- )
 5716:  POSTPONE AGAIN
 5717:  POSTPONE THEN ; immediate
 5718: @end example
 5719: 
 5720: @noindent
 5721: and then using these to create the control structure:
 5722: 
 5723: @example
 5724: BEGIN
 5725:   ...
 5726: WHILE
 5727:   ...
 5728: REPEAT
 5729: @end example
 5730: 
 5731: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5732: @code{WHILE} are predefined, so in this example it would not be
 5733: necessary to define them.
 5734: 
 5735: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5736: @subsection Calls and returns
 5737: @cindex calling a definition
 5738: @cindex returning from a definition
 5739: 
 5740: @cindex recursive definitions
 5741: A definition can be called simply be writing the name of the definition
 5742: to be called. Normally a definition is invisible during its own
 5743: definition. If you want to write a directly recursive definition, you
 5744: can use @code{recursive} to make the current definition visible, or
 5745: @code{recurse} to call the current definition directly.
 5746: 
 5747: 
 5748: doc-recursive
 5749: doc-recurse
 5750: 
 5751: 
 5752: @comment TODO add example of the two recursion methods
 5753: @quotation
 5754: @progstyle
 5755: I prefer using @code{recursive} to @code{recurse}, because calling the
 5756: definition by name is more descriptive (if the name is well-chosen) than
 5757: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5758: implementation, it is much better to read (and think) ``now sort the
 5759: partitions'' than to read ``now do a recursive call''.
 5760: @end quotation
 5761: 
 5762: For mutual recursion, use @code{Defer}red words, like this:
 5763: 
 5764: @example
 5765: Defer foo
 5766: 
 5767: : bar ( ... -- ... )
 5768:  ... foo ... ;
 5769: 
 5770: :noname ( ... -- ... )
 5771:  ... bar ... ;
 5772: IS foo
 5773: @end example
 5774: 
 5775: Deferred words are discussed in more detail in @ref{Deferred Words}.
 5776: 
 5777: The current definition returns control to the calling definition when
 5778: the end of the definition is reached or @code{EXIT} is encountered.
 5779: 
 5780: doc-exit
 5781: doc-;s
 5782: 
 5783: 
 5784: @node Exception Handling,  , Calls and returns, Control Structures
 5785: @subsection Exception Handling
 5786: @cindex exceptions
 5787: 
 5788: @c quit is a very bad idea for error handling, 
 5789: @c because it does not translate into a THROW
 5790: @c it also does not belong into this chapter
 5791: 
 5792: If a word detects an error condition that it cannot handle, it can
 5793: @code{throw} an exception.  In the simplest case, this will terminate
 5794: your program, and report an appropriate error.
 5795: 
 5796: doc-throw
 5797: 
 5798: @code{Throw} consumes a cell-sized error number on the stack. There are
 5799: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5800: Gforth (and most other systems) you can use the iors produced by various
 5801: words as error numbers (e.g., a typical use of @code{allocate} is
 5802: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5803: to define your own error numbers (with decent error reporting); an ANS
 5804: Forth version of this word (but without the error messages) is available
 5805: in @code{compat/except.fs}.  And finally, you can use your own error
 5806: numbers (anything outside the range -4095..0), but won't get nice error
 5807: messages, only numbers.  For example, try:
 5808: 
 5809: @example
 5810: -10 throw                    \ ANS defined
 5811: -267 throw                   \ system defined
 5812: s" my error" exception throw \ user defined
 5813: 7 throw                      \ arbitrary number
 5814: @end example
 5815: 
 5816: doc---exception-exception
 5817: 
 5818: A common idiom to @code{THROW} a specific error if a flag is true is
 5819: this:
 5820: 
 5821: @example
 5822: @code{( flag ) 0<> @i{errno} and throw}
 5823: @end example
 5824: 
 5825: Your program can provide exception handlers to catch exceptions.  An
 5826: exception handler can be used to correct the problem, or to clean up
 5827: some data structures and just throw the exception to the next exception
 5828: handler.  Note that @code{throw} jumps to the dynamically innermost
 5829: exception handler.  The system's exception handler is outermost, and just
 5830: prints an error and restarts command-line interpretation (or, in batch
 5831: mode (i.e., while processing the shell command line), leaves Gforth).
 5832: 
 5833: The ANS Forth way to catch exceptions is @code{catch}:
 5834: 
 5835: doc-catch
 5836: doc-nothrow
 5837: 
 5838: The most common use of exception handlers is to clean up the state when
 5839: an error happens.  E.g.,
 5840: 
 5841: @example
 5842: base @ >r hex \ actually the hex should be inside foo, or we h
 5843: ['] foo catch ( nerror|0 )
 5844: r> base !
 5845: ( nerror|0 ) throw \ pass it on
 5846: @end example
 5847: 
 5848: A use of @code{catch} for handling the error @code{myerror} might look
 5849: like this:
 5850: 
 5851: @example
 5852: ['] foo catch
 5853: CASE
 5854:   myerror OF ... ( do something about it ) nothrow ENDOF
 5855:   dup throw \ default: pass other errors on, do nothing on non-errors
 5856: ENDCASE
 5857: @end example
 5858: 
 5859: Having to wrap the code into a separate word is often cumbersome,
 5860: therefore Gforth provides an alternative syntax:
 5861: 
 5862: @example
 5863: TRY
 5864:   @i{code1}
 5865:   IFERROR
 5866:     @i{code2}
 5867:   THEN
 5868:   @i{code3}
 5869: ENDTRY
 5870: @end example
 5871: 
 5872: This performs @i{code1}.  If @i{code1} completes normally, execution
 5873: continues with @i{code3}.  If there is an exception in @i{code1} or
 5874: before @code{endtry}, the stacks are reset to the depth during
 5875: @code{try}, the throw value is pushed on the data stack, and execution
 5876: constinues at @i{code2}, and finally falls through to @i{code3}.
 5877: 
 5878: doc-try
 5879: doc-endtry
 5880: doc-iferror
 5881: 
 5882: If you don't need @i{code2}, you can write @code{restore} instead of
 5883: @code{iferror then}:
 5884: 
 5885: @example
 5886: TRY
 5887:   @i{code1}
 5888: RESTORE
 5889:   @i{code3}
 5890: ENDTRY
 5891: @end example
 5892: 
 5893: @cindex unwind-protect
 5894: The cleanup example from above in this syntax:
 5895: 
 5896: @example
 5897: base @@ @{ oldbase @}
 5898: TRY
 5899:   hex foo \ now the hex is placed correctly
 5900:   0       \ value for throw
 5901: RESTORE
 5902:   oldbase base !
 5903: ENDTRY
 5904: throw
 5905: @end example
 5906: 
 5907: An additional advantage of this variant is that an exception between
 5908: @code{restore} and @code{endtry} (e.g., from the user pressing
 5909: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
 5910: so the base will be restored under all circumstances.
 5911: 
 5912: However, you have to ensure that this code does not cause an exception
 5913: itself, otherwise the @code{iferror}/@code{restore} code will loop.
 5914: Moreover, you should also make sure that the stack contents needed by
 5915: the @code{iferror}/@code{restore} code exist everywhere between
 5916: @code{try} and @code{endtry}; in our example this is achived by
 5917: putting the data in a local before the @code{try} (you cannot use the
 5918: return stack because the exception frame (@i{sys1}) is in the way
 5919: there).
 5920: 
 5921: This kind of usage corresponds to Lisp's @code{unwind-protect}.
 5922: 
 5923: @cindex @code{recover} (old Gforth versions)
 5924: If you do not want this exception-restarting behaviour, you achieve
 5925: this as follows:
 5926: 
 5927: @example
 5928: TRY
 5929:   @i{code1}
 5930: ENDTRY-IFERROR
 5931:   @i{code2}
 5932: THEN
 5933: @end example
 5934: 
 5935: If there is an exception in @i{code1}, then @i{code2} is executed,
 5936: otherwise execution continues behind the @code{then} (or in a possible
 5937: @code{else} branch).  This corresponds to the construct
 5938: 
 5939: @example
 5940: TRY
 5941:   @i{code1}
 5942: RECOVER
 5943:   @i{code2}
 5944: ENDTRY
 5945: @end example
 5946: 
 5947: in Gforth before version 0.7.  So you can directly replace
 5948: @code{recover}-using code; however, we recommend that you check if it
 5949: would not be better to use one of the other @code{try} variants while
 5950: you are at it.
 5951: 
 5952: To ease the transition, Gforth provides two compatibility files:
 5953: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
 5954: ... then} syntax (but not @code{iferror} or @code{restore}) for old
 5955: systems; @file{recover-endtry.fs} provides the @code{try ... recover
 5956: ... endtry} syntax on new systems, so you can use that file as a
 5957: stopgap to run old programs.  Both files work on any system (they just
 5958: do nothing if the system already has the syntax it implements), so you
 5959: can unconditionally @code{require} one of these files, even if you use
 5960: a mix old and new systems.
 5961: 
 5962: doc-restore
 5963: doc-endtry-iferror
 5964: 
 5965: Here's the error handling example:
 5966: 
 5967: @example
 5968: TRY
 5969:   foo
 5970: ENDTRY-IFERROR
 5971:   CASE
 5972:     myerror OF ... ( do something about it ) nothrow ENDOF
 5973:     throw \ pass other errors on
 5974:   ENDCASE
 5975: THEN
 5976: @end example
 5977: 
 5978: @progstyle
 5979: As usual, you should ensure that the stack depth is statically known at
 5980: the end: either after the @code{throw} for passing on errors, or after
 5981: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5982: selection construct for handling the error).
 5983: 
 5984: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5985: and you can provide an error message.  @code{Abort} just produces an
 5986: ``Aborted'' error.
 5987: 
 5988: The problem with these words is that exception handlers cannot
 5989: differentiate between different @code{abort"}s; they just look like
 5990: @code{-2 throw} to them (the error message cannot be accessed by
 5991: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5992: exception handlers.
 5993: 
 5994: doc-abort"
 5995: doc-abort
 5996: 
 5997: 
 5998: 
 5999: @c -------------------------------------------------------------
 6000: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 6001: @section Defining Words
 6002: @cindex defining words
 6003: 
 6004: Defining words are used to extend Forth by creating new entries in the dictionary.
 6005: 
 6006: @menu
 6007: * CREATE::                      
 6008: * Variables::                   Variables and user variables
 6009: * Constants::                   
 6010: * Values::                      Initialised variables
 6011: * Colon Definitions::           
 6012: * Anonymous Definitions::       Definitions without names
 6013: * Supplying names::             Passing definition names as strings
 6014: * User-defined Defining Words::  
 6015: * Deferred Words::              Allow forward references
 6016: * Aliases::                     
 6017: @end menu
 6018: 
 6019: @node CREATE, Variables, Defining Words, Defining Words
 6020: @subsection @code{CREATE}
 6021: @cindex simple defining words
 6022: @cindex defining words, simple
 6023: 
 6024: Defining words are used to create new entries in the dictionary. The
 6025: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 6026: this:
 6027: 
 6028: @example
 6029: CREATE new-word1
 6030: @end example
 6031: 
 6032: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 6033: input stream (@code{new-word1} in our example).  It generates a
 6034: dictionary entry for @code{new-word1}. When @code{new-word1} is
 6035: executed, all that it does is leave an address on the stack. The address
 6036: represents the value of the data space pointer (@code{HERE}) at the time
 6037: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 6038: associating a name with the address of a region of memory.
 6039: 
 6040: doc-create
 6041: 
 6042: Note that in ANS Forth guarantees only for @code{create} that its body
 6043: is in dictionary data space (i.e., where @code{here}, @code{allot}
 6044: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 6045: @code{create}d words can be modified with @code{does>}
 6046: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 6047: can only be applied to @code{create}d words.
 6048: 
 6049: By extending this example to reserve some memory in data space, we end
 6050: up with something like a @i{variable}. Here are two different ways to do
 6051: it:
 6052: 
 6053: @example
 6054: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 6055: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 6056: @end example
 6057: 
 6058: The variable can be examined and modified using @code{@@} (``fetch'') and
 6059: @code{!} (``store'') like this:
 6060: 
 6061: @example
 6062: new-word2 @@ .      \ get address, fetch from it and display
 6063: 1234 new-word2 !   \ new value, get address, store to it
 6064: @end example
 6065: 
 6066: @cindex arrays
 6067: A similar mechanism can be used to create arrays. For example, an
 6068: 80-character text input buffer:
 6069: 
 6070: @example
 6071: CREATE text-buf 80 chars allot
 6072: 
 6073: text-buf 0 chars + c@@ \ the 1st character (offset 0)
 6074: text-buf 3 chars + c@@ \ the 4th character (offset 3)
 6075: @end example
 6076: 
 6077: You can build arbitrarily complex data structures by allocating
 6078: appropriate areas of memory. For further discussions of this, and to
 6079: learn about some Gforth tools that make it easier,
 6080: @xref{Structures}.
 6081: 
 6082: 
 6083: @node Variables, Constants, CREATE, Defining Words
 6084: @subsection Variables
 6085: @cindex variables
 6086: 
 6087: The previous section showed how a sequence of commands could be used to
 6088: generate a variable.  As a final refinement, the whole code sequence can
 6089: be wrapped up in a defining word (pre-empting the subject of the next
 6090: section), making it easier to create new variables:
 6091: 
 6092: @example
 6093: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 6094: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 6095: 
 6096: myvariableX foo \ variable foo starts off with an unknown value
 6097: myvariable0 joe \ whilst joe is initialised to 0
 6098: 
 6099: 45 3 * foo !   \ set foo to 135
 6100: 1234 joe !     \ set joe to 1234
 6101: 3 joe +!       \ increment joe by 3.. to 1237
 6102: @end example
 6103: 
 6104: Not surprisingly, there is no need to define @code{myvariable}, since
 6105: Forth already has a definition @code{Variable}. ANS Forth does not
 6106: guarantee that a @code{Variable} is initialised when it is created
 6107: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 6108: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 6109: like @code{myvariable0}). Forth also provides @code{2Variable} and
 6110: @code{fvariable} for double and floating-point variables, respectively
 6111: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 6112: store a boolean, you can use @code{on} and @code{off} to toggle its
 6113: state.
 6114: 
 6115: doc-variable
 6116: doc-2variable
 6117: doc-fvariable
 6118: 
 6119: @cindex user variables
 6120: @cindex user space
 6121: The defining word @code{User} behaves in the same way as @code{Variable}.
 6122: The difference is that it reserves space in @i{user (data) space} rather
 6123: than normal data space. In a Forth system that has a multi-tasker, each
 6124: task has its own set of user variables.
 6125: 
 6126: doc-user
 6127: @c doc-udp
 6128: @c doc-uallot
 6129: 
 6130: @comment TODO is that stuff about user variables strictly correct? Is it
 6131: @comment just terminal tasks that have user variables?
 6132: @comment should document tasker.fs (with some examples) elsewhere
 6133: @comment in this manual, then expand on user space and user variables.
 6134: 
 6135: @node Constants, Values, Variables, Defining Words
 6136: @subsection Constants
 6137: @cindex constants
 6138: 
 6139: @code{Constant} allows you to declare a fixed value and refer to it by
 6140: name. For example:
 6141: 
 6142: @example
 6143: 12 Constant INCHES-PER-FOOT
 6144: 3E+08 fconstant SPEED-O-LIGHT
 6145: @end example
 6146: 
 6147: A @code{Variable} can be both read and written, so its run-time
 6148: behaviour is to supply an address through which its current value can be
 6149: manipulated. In contrast, the value of a @code{Constant} cannot be
 6150: changed once it has been declared@footnote{Well, often it can be -- but
 6151: not in a Standard, portable way. It's safer to use a @code{Value} (read
 6152: on).} so it's not necessary to supply the address -- it is more
 6153: efficient to return the value of the constant directly. That's exactly
 6154: what happens; the run-time effect of a constant is to put its value on
 6155: the top of the stack (You can find one
 6156: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 6157: 
 6158: Forth also provides @code{2Constant} and @code{fconstant} for defining
 6159: double and floating-point constants, respectively.
 6160: 
 6161: doc-constant
 6162: doc-2constant
 6163: doc-fconstant
 6164: 
 6165: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6166: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6167: @c constant, use it and then delete the definition of the constant..
 6168: 
 6169: @c anton->An ANS Forth system can compile a constant to a literal; On
 6170: @c decompilation you would see only the number, just as if it had been used
 6171: @c in the first place.  The word will stay, of course, but it will only be
 6172: @c used by the text interpreter (no run-time duties, except when it is 
 6173: @c POSTPONEd or somesuch).
 6174: 
 6175: @c nac:
 6176: @c I agree that it's rather deep, but IMO it is an important difference
 6177: @c relative to other programming languages.. often it's annoying: it
 6178: @c certainly changes my programming style relative to C.
 6179: 
 6180: @c anton: In what way?
 6181: 
 6182: Constants in Forth behave differently from their equivalents in other
 6183: programming languages. In other languages, a constant (such as an EQU in
 6184: assembler or a #define in C) only exists at compile-time; in the
 6185: executable program the constant has been translated into an absolute
 6186: number and, unless you are using a symbolic debugger, it's impossible to
 6187: know what abstract thing that number represents. In Forth a constant has
 6188: an entry in the header space and remains there after the code that uses
 6189: it has been defined. In fact, it must remain in the dictionary since it
 6190: has run-time duties to perform. For example:
 6191: 
 6192: @example
 6193: 12 Constant INCHES-PER-FOOT
 6194: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6195: @end example
 6196: 
 6197: @cindex in-lining of constants
 6198: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6199: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6200: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6201: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6202: attempt to optimise constants by in-lining them where they are used. You
 6203: can force Gforth to in-line a constant like this:
 6204: 
 6205: @example
 6206: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6207: @end example
 6208: 
 6209: If you use @code{see} to decompile @i{this} version of
 6210: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6211: longer present. To understand how this works, read
 6212: @ref{Interpret/Compile states}, and @ref{Literals}.
 6213: 
 6214: In-lining constants in this way might improve execution time
 6215: fractionally, and can ensure that a constant is now only referenced at
 6216: compile-time. However, the definition of the constant still remains in
 6217: the dictionary. Some Forth compilers provide a mechanism for controlling
 6218: a second dictionary for holding transient words such that this second
 6219: dictionary can be deleted later in order to recover memory
 6220: space. However, there is no standard way of doing this.
 6221: 
 6222: 
 6223: @node Values, Colon Definitions, Constants, Defining Words
 6224: @subsection Values
 6225: @cindex values
 6226: 
 6227: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6228: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6229: (not in ANS Forth) you can access (and change) a @code{value} also with
 6230: @code{>body}.
 6231: 
 6232: Here are some
 6233: examples:
 6234: 
 6235: @example
 6236: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6237: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6238: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6239: APPLES              \ puts 35 on the top of the stack.
 6240: @end example
 6241: 
 6242: doc-value
 6243: doc-to
 6244: 
 6245: 
 6246: 
 6247: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6248: @subsection Colon Definitions
 6249: @cindex colon definitions
 6250: 
 6251: @example
 6252: : name ( ... -- ... )
 6253:     word1 word2 word3 ;
 6254: @end example
 6255: 
 6256: @noindent
 6257: Creates a word called @code{name} that, upon execution, executes
 6258: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6259: 
 6260: The explanation above is somewhat superficial. For simple examples of
 6261: colon definitions see @ref{Your first definition}.  For an in-depth
 6262: discussion of some of the issues involved, @xref{Interpretation and
 6263: Compilation Semantics}.
 6264: 
 6265: doc-:
 6266: doc-;
 6267: 
 6268: 
 6269: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6270: @subsection Anonymous Definitions
 6271: @cindex colon definitions
 6272: @cindex defining words without name
 6273: 
 6274: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6275: name. You can do this with:
 6276: 
 6277: doc-:noname
 6278: 
 6279: This leaves the execution token for the word on the stack after the
 6280: closing @code{;}. Here's an example in which a deferred word is
 6281: initialised with an @code{xt} from an anonymous colon definition:
 6282: 
 6283: @example
 6284: Defer deferred
 6285: :noname ( ... -- ... )
 6286:   ... ;
 6287: IS deferred
 6288: @end example
 6289: 
 6290: @noindent
 6291: Gforth provides an alternative way of doing this, using two separate
 6292: words:
 6293: 
 6294: doc-noname
 6295: @cindex execution token of last defined word
 6296: doc-latestxt
 6297: 
 6298: @noindent
 6299: The previous example can be rewritten using @code{noname} and
 6300: @code{latestxt}:
 6301: 
 6302: @example
 6303: Defer deferred
 6304: noname : ( ... -- ... )
 6305:   ... ;
 6306: latestxt IS deferred
 6307: @end example
 6308: 
 6309: @noindent
 6310: @code{noname} works with any defining word, not just @code{:}.
 6311: 
 6312: @code{latestxt} also works when the last word was not defined as
 6313: @code{noname}.  It does not work for combined words, though.  It also has
 6314: the useful property that is is valid as soon as the header for a
 6315: definition has been built. Thus:
 6316: 
 6317: @example
 6318: latestxt . : foo [ latestxt . ] ; ' foo .
 6319: @end example
 6320: 
 6321: @noindent
 6322: prints 3 numbers; the last two are the same.
 6323: 
 6324: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6325: @subsection Supplying the name of a defined word
 6326: @cindex names for defined words
 6327: @cindex defining words, name given in a string
 6328: 
 6329: By default, a defining word takes the name for the defined word from the
 6330: input stream. Sometimes you want to supply the name from a string. You
 6331: can do this with:
 6332: 
 6333: doc-nextname
 6334: 
 6335: For example:
 6336: 
 6337: @example
 6338: s" foo" nextname create
 6339: @end example
 6340: 
 6341: @noindent
 6342: is equivalent to:
 6343: 
 6344: @example
 6345: create foo
 6346: @end example
 6347: 
 6348: @noindent
 6349: @code{nextname} works with any defining word.
 6350: 
 6351: 
 6352: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
 6353: @subsection User-defined Defining Words
 6354: @cindex user-defined defining words
 6355: @cindex defining words, user-defined
 6356: 
 6357: You can create a new defining word by wrapping defining-time code around
 6358: an existing defining word and putting the sequence in a colon
 6359: definition. 
 6360: 
 6361: @c anton: This example is very complex and leads in a quite different
 6362: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6363: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6364: @c subsection of Defining Words)
 6365: 
 6366: For example, suppose that you have a word @code{stats} that
 6367: gathers statistics about colon definitions given the @i{xt} of the
 6368: definition, and you want every colon definition in your application to
 6369: make a call to @code{stats}. You can define and use a new version of
 6370: @code{:} like this:
 6371: 
 6372: @example
 6373: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6374:   ... ;  \ other code
 6375: 
 6376: : my: : latestxt postpone literal ['] stats compile, ;
 6377: 
 6378: my: foo + - ;
 6379: @end example
 6380: 
 6381: When @code{foo} is defined using @code{my:} these steps occur:
 6382: 
 6383: @itemize @bullet
 6384: @item
 6385: @code{my:} is executed.
 6386: @item
 6387: The @code{:} within the definition (the one between @code{my:} and
 6388: @code{latestxt}) is executed, and does just what it always does; it parses
 6389: the input stream for a name, builds a dictionary header for the name
 6390: @code{foo} and switches @code{state} from interpret to compile.
 6391: @item
 6392: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6393: being defined -- @code{foo} -- onto the stack.
 6394: @item
 6395: The code that was produced by @code{postpone literal} is executed; this
 6396: causes the value on the stack to be compiled as a literal in the code
 6397: area of @code{foo}.
 6398: @item
 6399: The code @code{['] stats} compiles a literal into the definition of
 6400: @code{my:}. When @code{compile,} is executed, that literal -- the
 6401: execution token for @code{stats} -- is layed down in the code area of
 6402: @code{foo} , following the literal@footnote{Strictly speaking, the
 6403: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6404: in the code area is implementation-dependent. A threaded implementation
 6405: might spit out the execution token directly whilst another
 6406: implementation might spit out a native code sequence.}.
 6407: @item
 6408: At this point, the execution of @code{my:} is complete, and control
 6409: returns to the text interpreter. The text interpreter is in compile
 6410: state, so subsequent text @code{+ -} is compiled into the definition of
 6411: @code{foo} and the @code{;} terminates the definition as always.
 6412: @end itemize
 6413: 
 6414: You can use @code{see} to decompile a word that was defined using
 6415: @code{my:} and see how it is different from a normal @code{:}
 6416: definition. For example:
 6417: 
 6418: @example
 6419: : bar + - ;  \ like foo but using : rather than my:
 6420: see bar
 6421: : bar
 6422:   + - ;
 6423: see foo
 6424: : foo
 6425:   107645672 stats + - ;
 6426: 
 6427: \ use ' foo . to show that 107645672 is the xt for foo
 6428: @end example
 6429: 
 6430: You can use techniques like this to make new defining words in terms of
 6431: @i{any} existing defining word.
 6432: 
 6433: 
 6434: @cindex defining defining words
 6435: @cindex @code{CREATE} ... @code{DOES>}
 6436: If you want the words defined with your defining words to behave
 6437: differently from words defined with standard defining words, you can
 6438: write your defining word like this:
 6439: 
 6440: @example
 6441: : def-word ( "name" -- )
 6442:     CREATE @i{code1}
 6443: DOES> ( ... -- ... )
 6444:     @i{code2} ;
 6445: 
 6446: def-word name
 6447: @end example
 6448: 
 6449: @cindex child words
 6450: This fragment defines a @dfn{defining word} @code{def-word} and then
 6451: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6452: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6453: is not executed at this time. The word @code{name} is sometimes called a
 6454: @dfn{child} of @code{def-word}.
 6455: 
 6456: When you execute @code{name}, the address of the body of @code{name} is
 6457: put on the data stack and @i{code2} is executed (the address of the body
 6458: of @code{name} is the address @code{HERE} returns immediately after the
 6459: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6460: default).
 6461: 
 6462: @c anton:
 6463: @c www.dictionary.com says:
 6464: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6465: @c several generations of absence, usually caused by the chance
 6466: @c recombination of genes.  2.An individual or a part that exhibits
 6467: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6468: @c of previous behavior after a period of absence.
 6469: @c
 6470: @c Doesn't seem to fit.
 6471: 
 6472: @c @cindex atavism in child words
 6473: You can use @code{def-word} to define a set of child words that behave
 6474: similarly; they all have a common run-time behaviour determined by
 6475: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6476: body of the child word. The structure of the data is common to all
 6477: children of @code{def-word}, but the data values are specific -- and
 6478: private -- to each child word. When a child word is executed, the
 6479: address of its private data area is passed as a parameter on TOS to be
 6480: used and manipulated@footnote{It is legitimate both to read and write to
 6481: this data area.} by @i{code2}.
 6482: 
 6483: The two fragments of code that make up the defining words act (are
 6484: executed) at two completely separate times:
 6485: 
 6486: @itemize @bullet
 6487: @item
 6488: At @i{define time}, the defining word executes @i{code1} to generate a
 6489: child word
 6490: @item
 6491: At @i{child execution time}, when a child word is invoked, @i{code2}
 6492: is executed, using parameters (data) that are private and specific to
 6493: the child word.
 6494: @end itemize
 6495: 
 6496: Another way of understanding the behaviour of @code{def-word} and
 6497: @code{name} is to say that, if you make the following definitions:
 6498: @example
 6499: : def-word1 ( "name" -- )
 6500:     CREATE @i{code1} ;
 6501: 
 6502: : action1 ( ... -- ... )
 6503:     @i{code2} ;
 6504: 
 6505: def-word1 name1
 6506: @end example
 6507: 
 6508: @noindent
 6509: Then using @code{name1 action1} is equivalent to using @code{name}.
 6510: 
 6511: The classic example is that you can define @code{CONSTANT} in this way:
 6512: 
 6513: @example
 6514: : CONSTANT ( w "name" -- )
 6515:     CREATE ,
 6516: DOES> ( -- w )
 6517:     @@ ;
 6518: @end example
 6519: 
 6520: @comment There is a beautiful description of how this works and what
 6521: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6522: @comment commentary on the Counting Fruits problem.
 6523: 
 6524: When you create a constant with @code{5 CONSTANT five}, a set of
 6525: define-time actions take place; first a new word @code{five} is created,
 6526: then the value 5 is laid down in the body of @code{five} with
 6527: @code{,}. When @code{five} is executed, the address of the body is put on
 6528: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6529: no code of its own; it simply contains a data field and a pointer to the
 6530: code that follows @code{DOES>} in its defining word. That makes words
 6531: created in this way very compact.
 6532: 
 6533: The final example in this section is intended to remind you that space
 6534: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6535: both read and written by a Standard program@footnote{Exercise: use this
 6536: example as a starting point for your own implementation of @code{Value}
 6537: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6538: @code{[']}.}:
 6539: 
 6540: @example
 6541: : foo ( "name" -- )
 6542:     CREATE -1 ,
 6543: DOES> ( -- )
 6544:     @@ . ;
 6545: 
 6546: foo first-word
 6547: foo second-word
 6548: 
 6549: 123 ' first-word >BODY !
 6550: @end example
 6551: 
 6552: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6553: have executed it to get the address of its data field. However, since it
 6554: was defined to have @code{DOES>} actions, its execution semantics are to
 6555: perform those @code{DOES>} actions. To get the address of its data field
 6556: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6557: translate the xt into the address of the data field.  When you execute
 6558: @code{first-word}, it will display @code{123}. When you execute
 6559: @code{second-word} it will display @code{-1}.
 6560: 
 6561: @cindex stack effect of @code{DOES>}-parts
 6562: @cindex @code{DOES>}-parts, stack effect
 6563: In the examples above the stack comment after the @code{DOES>} specifies
 6564: the stack effect of the defined words, not the stack effect of the
 6565: following code (the following code expects the address of the body on
 6566: the top of stack, which is not reflected in the stack comment). This is
 6567: the convention that I use and recommend (it clashes a bit with using
 6568: locals declarations for stack effect specification, though).
 6569: 
 6570: @menu
 6571: * CREATE..DOES> applications::  
 6572: * CREATE..DOES> details::       
 6573: * Advanced does> usage example::  
 6574: * Const-does>::                 
 6575: @end menu
 6576: 
 6577: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6578: @subsubsection Applications of @code{CREATE..DOES>}
 6579: @cindex @code{CREATE} ... @code{DOES>}, applications
 6580: 
 6581: You may wonder how to use this feature. Here are some usage patterns:
 6582: 
 6583: @cindex factoring similar colon definitions
 6584: When you see a sequence of code occurring several times, and you can
 6585: identify a meaning, you will factor it out as a colon definition. When
 6586: you see similar colon definitions, you can factor them using
 6587: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6588: that look very similar:
 6589: @example
 6590: : ori, ( reg-target reg-source n -- )
 6591:     0 asm-reg-reg-imm ;
 6592: : andi, ( reg-target reg-source n -- )
 6593:     1 asm-reg-reg-imm ;
 6594: @end example
 6595: 
 6596: @noindent
 6597: This could be factored with:
 6598: @example
 6599: : reg-reg-imm ( op-code -- )
 6600:     CREATE ,
 6601: DOES> ( reg-target reg-source n -- )
 6602:     @@ asm-reg-reg-imm ;
 6603: 
 6604: 0 reg-reg-imm ori,
 6605: 1 reg-reg-imm andi,
 6606: @end example
 6607: 
 6608: @cindex currying
 6609: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6610: supply a part of the parameters for a word (known as @dfn{currying} in
 6611: the functional language community). E.g., @code{+} needs two
 6612: parameters. Creating versions of @code{+} with one parameter fixed can
 6613: be done like this:
 6614: 
 6615: @example
 6616: : curry+ ( n1 "name" -- )
 6617:     CREATE ,
 6618: DOES> ( n2 -- n1+n2 )
 6619:     @@ + ;
 6620: 
 6621:  3 curry+ 3+
 6622: -2 curry+ 2-
 6623: @end example
 6624: 
 6625: 
 6626: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6627: @subsubsection The gory details of @code{CREATE..DOES>}
 6628: @cindex @code{CREATE} ... @code{DOES>}, details
 6629: 
 6630: doc-does>
 6631: 
 6632: @cindex @code{DOES>} in a separate definition
 6633: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6634: same definition; you can put the @code{DOES>}-part in a separate
 6635: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6636: @example
 6637: : does1 
 6638: DOES> ( ... -- ... )
 6639:     ... ;
 6640: 
 6641: : does2
 6642: DOES> ( ... -- ... )
 6643:     ... ;
 6644: 
 6645: : def-word ( ... -- ... )
 6646:     create ...
 6647:     IF
 6648:        does1
 6649:     ELSE
 6650:        does2
 6651:     ENDIF ;
 6652: @end example
 6653: 
 6654: In this example, the selection of whether to use @code{does1} or
 6655: @code{does2} is made at definition-time; at the time that the child word is
 6656: @code{CREATE}d.
 6657: 
 6658: @cindex @code{DOES>} in interpretation state
 6659: In a standard program you can apply a @code{DOES>}-part only if the last
 6660: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6661: will override the behaviour of the last word defined in any case. In a
 6662: standard program, you can use @code{DOES>} only in a colon
 6663: definition. In Gforth, you can also use it in interpretation state, in a
 6664: kind of one-shot mode; for example:
 6665: @example
 6666: CREATE name ( ... -- ... )
 6667:   @i{initialization}
 6668: DOES>
 6669:   @i{code} ;
 6670: @end example
 6671: 
 6672: @noindent
 6673: is equivalent to the standard:
 6674: @example
 6675: :noname
 6676: DOES>
 6677:     @i{code} ;
 6678: CREATE name EXECUTE ( ... -- ... )
 6679:     @i{initialization}
 6680: @end example
 6681: 
 6682: doc->body
 6683: 
 6684: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
 6685: @subsubsection Advanced does> usage example
 6686: 
 6687: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6688: for disassembling instructions, that follow a very repetetive scheme:
 6689: 
 6690: @example
 6691: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6692: @var{entry-num} cells @var{table} + !
 6693: @end example
 6694: 
 6695: Of course, this inspires the idea to factor out the commonalities to
 6696: allow a definition like
 6697: 
 6698: @example
 6699: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6700: @end example
 6701: 
 6702: The parameters @var{disasm-operands} and @var{table} are usually
 6703: correlated.  Moreover, before I wrote the disassembler, there already
 6704: existed code that defines instructions like this:
 6705: 
 6706: @example
 6707: @var{entry-num} @var{inst-format} @var{inst-name}
 6708: @end example
 6709: 
 6710: This code comes from the assembler and resides in
 6711: @file{arch/mips/insts.fs}.
 6712: 
 6713: So I had to define the @var{inst-format} words that performed the scheme
 6714: above when executed.  At first I chose to use run-time code-generation:
 6715: 
 6716: @example
 6717: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6718:   :noname Postpone @var{disasm-operands}
 6719:   name Postpone sliteral Postpone type Postpone ;
 6720:   swap cells @var{table} + ! ;
 6721: @end example
 6722: 
 6723: Note that this supplies the other two parameters of the scheme above.
 6724: 
 6725: An alternative would have been to write this using
 6726: @code{create}/@code{does>}:
 6727: 
 6728: @example
 6729: : @var{inst-format} ( entry-num "name" -- )
 6730:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6731:   noname create , ( entry-num )
 6732:   latestxt swap cells @var{table} + !
 6733: does> ( addr w -- )
 6734:   \ disassemble instruction w at addr
 6735:   @@ >r 
 6736:   @var{disasm-operands}
 6737:   r> count type ;
 6738: @end example
 6739: 
 6740: Somehow the first solution is simpler, mainly because it's simpler to
 6741: shift a string from definition-time to use-time with @code{sliteral}
 6742: than with @code{string,} and friends.
 6743: 
 6744: I wrote a lot of words following this scheme and soon thought about
 6745: factoring out the commonalities among them.  Note that this uses a
 6746: two-level defining word, i.e., a word that defines ordinary defining
 6747: words.
 6748: 
 6749: This time a solution involving @code{postpone} and friends seemed more
 6750: difficult (try it as an exercise), so I decided to use a
 6751: @code{create}/@code{does>} word; since I was already at it, I also used
 6752: @code{create}/@code{does>} for the lower level (try using
 6753: @code{postpone} etc. as an exercise), resulting in the following
 6754: definition:
 6755: 
 6756: @example
 6757: : define-format ( disasm-xt table-xt -- )
 6758:     \ define an instruction format that uses disasm-xt for
 6759:     \ disassembling and enters the defined instructions into table
 6760:     \ table-xt
 6761:     create 2,
 6762: does> ( u "inst" -- )
 6763:     \ defines an anonymous word for disassembling instruction inst,
 6764:     \ and enters it as u-th entry into table-xt
 6765:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6766:     noname create 2,      \ define anonymous word
 6767:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6768: does> ( addr w -- )
 6769:     \ disassemble instruction w at addr
 6770:     2@@ >r ( addr w disasm-xt R: c-addr )
 6771:     execute ( R: c-addr ) \ disassemble operands
 6772:     r> count type ; \ print name 
 6773: @end example
 6774: 
 6775: Note that the tables here (in contrast to above) do the @code{cells +}
 6776: by themselves (that's why you have to pass an xt).  This word is used in
 6777: the following way:
 6778: 
 6779: @example
 6780: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6781: @end example
 6782: 
 6783: As shown above, the defined instruction format is then used like this:
 6784: 
 6785: @example
 6786: @var{entry-num} @var{inst-format} @var{inst-name}
 6787: @end example
 6788: 
 6789: In terms of currying, this kind of two-level defining word provides the
 6790: parameters in three stages: first @var{disasm-operands} and @var{table},
 6791: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6792: the instruction to be disassembled.  
 6793: 
 6794: Of course this did not quite fit all the instruction format names used
 6795: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6796: the parameters into the right form.
 6797: 
 6798: If you have trouble following this section, don't worry.  First, this is
 6799: involved and takes time (and probably some playing around) to
 6800: understand; second, this is the first two-level
 6801: @code{create}/@code{does>} word I have written in seventeen years of
 6802: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6803: have elected to use just a one-level defining word (with some repeating
 6804: of parameters when using the defining word). So it is not necessary to
 6805: understand this, but it may improve your understanding of Forth.
 6806: 
 6807: 
 6808: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
 6809: @subsubsection @code{Const-does>}
 6810: 
 6811: A frequent use of @code{create}...@code{does>} is for transferring some
 6812: values from definition-time to run-time.  Gforth supports this use with
 6813: 
 6814: doc-const-does>
 6815: 
 6816: A typical use of this word is:
 6817: 
 6818: @example
 6819: : curry+ ( n1 "name" -- )
 6820: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6821:     + ;
 6822: 
 6823: 3 curry+ 3+
 6824: @end example
 6825: 
 6826: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6827: definition to run-time.
 6828: 
 6829: The advantages of using @code{const-does>} are:
 6830: 
 6831: @itemize
 6832: 
 6833: @item
 6834: You don't have to deal with storing and retrieving the values, i.e.,
 6835: your program becomes more writable and readable.
 6836: 
 6837: @item
 6838: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6839: be optimized away (because you could change the data using
 6840: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6841: 
 6842: @end itemize
 6843: 
 6844: An ANS Forth implementation of @code{const-does>} is available in
 6845: @file{compat/const-does.fs}.
 6846: 
 6847: 
 6848: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
 6849: @subsection Deferred Words
 6850: @cindex deferred words
 6851: 
 6852: The defining word @code{Defer} allows you to define a word by name
 6853: without defining its behaviour; the definition of its behaviour is
 6854: deferred. Here are two situation where this can be useful:
 6855: 
 6856: @itemize @bullet
 6857: @item
 6858: Where you want to allow the behaviour of a word to be altered later, and
 6859: for all precompiled references to the word to change when its behaviour
 6860: is changed.
 6861: @item
 6862: For mutual recursion; @xref{Calls and returns}.
 6863: @end itemize
 6864: 
 6865: In the following example, @code{foo} always invokes the version of
 6866: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6867: always invokes the version that prints ``@code{Hello}''. There is no way
 6868: of getting @code{foo} to use the later version without re-ordering the
 6869: source code and recompiling it.
 6870: 
 6871: @example
 6872: : greet ." Good morning" ;
 6873: : foo ... greet ... ;
 6874: : greet ." Hello" ;
 6875: : bar ... greet ... ;
 6876: @end example
 6877: 
 6878: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6879: word. The behaviour of a @code{Defer}red word can be defined and
 6880: redefined at any time by using @code{IS} to associate the xt of a
 6881: previously-defined word with it. The previous example becomes:
 6882: 
 6883: @example
 6884: Defer greet ( -- )
 6885: : foo ... greet ... ;
 6886: : bar ... greet ... ;
 6887: : greet1 ( -- ) ." Good morning" ;
 6888: : greet2 ( -- ) ." Hello" ;
 6889: ' greet2 IS greet  \ make greet behave like greet2
 6890: @end example
 6891: 
 6892: @progstyle
 6893: You should write a stack comment for every deferred word, and put only
 6894: XTs into deferred words that conform to this stack effect.  Otherwise
 6895: it's too difficult to use the deferred word.
 6896: 
 6897: A deferred word can be used to improve the statistics-gathering example
 6898: from @ref{User-defined Defining Words}; rather than edit the
 6899: application's source code to change every @code{:} to a @code{my:}, do
 6900: this:
 6901: 
 6902: @example
 6903: : real: : ;     \ retain access to the original
 6904: defer :         \ redefine as a deferred word
 6905: ' my: IS :      \ use special version of :
 6906: \
 6907: \ load application here
 6908: \
 6909: ' real: IS :    \ go back to the original
 6910: @end example
 6911: 
 6912: 
 6913: One thing to note is that @code{IS} has special compilation semantics,
 6914: such that it parses the name at compile time (like @code{TO}):
 6915: 
 6916: @example
 6917: : set-greet ( xt -- )
 6918:   IS greet ;
 6919: 
 6920: ' greet1 set-greet
 6921: @end example
 6922: 
 6923: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6924: 
 6925: A deferred word can only inherit execution semantics from the xt
 6926: (because that is all that an xt can represent -- for more discussion of
 6927: this @pxref{Tokens for Words}); by default it will have default
 6928: interpretation and compilation semantics deriving from this execution
 6929: semantics.  However, you can change the interpretation and compilation
 6930: semantics of the deferred word in the usual ways:
 6931: 
 6932: @example
 6933: : bar .... ; immediate
 6934: Defer fred immediate
 6935: Defer jim
 6936: 
 6937: ' bar IS jim  \ jim has default semantics
 6938: ' bar IS fred \ fred is immediate
 6939: @end example
 6940: 
 6941: doc-defer
 6942: doc-defer!
 6943: doc-is
 6944: doc-defer@
 6945: doc-action-of
 6946: @comment TODO document these: what's defers [is]
 6947: doc-defers
 6948: 
 6949: @c Use @code{words-deferred} to see a list of deferred words.
 6950: 
 6951: Definitions of these words (except @code{defers}) in ANS Forth are
 6952: provided in @file{compat/defer.fs}.
 6953: 
 6954: 
 6955: @node Aliases,  , Deferred Words, Defining Words
 6956: @subsection Aliases
 6957: @cindex aliases
 6958: 
 6959: The defining word @code{Alias} allows you to define a word by name that
 6960: has the same behaviour as some other word. Here are two situation where
 6961: this can be useful:
 6962: 
 6963: @itemize @bullet
 6964: @item
 6965: When you want access to a word's definition from a different word list
 6966: (for an example of this, see the definition of the @code{Root} word list
 6967: in the Gforth source).
 6968: @item
 6969: When you want to create a synonym; a definition that can be known by
 6970: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6971: aliases).
 6972: @end itemize
 6973: 
 6974: Like deferred words, an alias has default compilation and interpretation
 6975: semantics at the beginning (not the modifications of the other word),
 6976: but you can change them in the usual ways (@code{immediate},
 6977: @code{compile-only}). For example:
 6978: 
 6979: @example
 6980: : foo ... ; immediate
 6981: 
 6982: ' foo Alias bar \ bar is not an immediate word
 6983: ' foo Alias fooby immediate \ fooby is an immediate word
 6984: @end example
 6985: 
 6986: Words that are aliases have the same xt, different headers in the
 6987: dictionary, and consequently different name tokens (@pxref{Tokens for
 6988: Words}) and possibly different immediate flags.  An alias can only have
 6989: default or immediate compilation semantics; you can define aliases for
 6990: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6991: 
 6992: doc-alias
 6993: 
 6994: 
 6995: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6996: @section Interpretation and Compilation Semantics
 6997: @cindex semantics, interpretation and compilation
 6998: 
 6999: @c !! state and ' are used without explanation
 7000: @c example for immediate/compile-only? or is the tutorial enough
 7001: 
 7002: @cindex interpretation semantics
 7003: The @dfn{interpretation semantics} of a (named) word are what the text
 7004: interpreter does when it encounters the word in interpret state. It also
 7005: appears in some other contexts, e.g., the execution token returned by
 7006: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 7007: (in other words, @code{' @i{word} execute} is equivalent to
 7008: interpret-state text interpretation of @code{@i{word}}).
 7009: 
 7010: @cindex compilation semantics
 7011: The @dfn{compilation semantics} of a (named) word are what the text
 7012: interpreter does when it encounters the word in compile state. It also
 7013: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 7014: compiles@footnote{In standard terminology, ``appends to the current
 7015: definition''.} the compilation semantics of @i{word}.
 7016: 
 7017: @cindex execution semantics
 7018: The standard also talks about @dfn{execution semantics}. They are used
 7019: only for defining the interpretation and compilation semantics of many
 7020: words. By default, the interpretation semantics of a word are to
 7021: @code{execute} its execution semantics, and the compilation semantics of
 7022: a word are to @code{compile,} its execution semantics.@footnote{In
 7023: standard terminology: The default interpretation semantics are its
 7024: execution semantics; the default compilation semantics are to append its
 7025: execution semantics to the execution semantics of the current
 7026: definition.}
 7027: 
 7028: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 7029: the text interpreter, ticked, or @code{postpone}d, so they have no
 7030: interpretation or compilation semantics.  Their behaviour is represented
 7031: by their XT (@pxref{Tokens for Words}), and we call it execution
 7032: semantics, too.
 7033: 
 7034: @comment TODO expand, make it co-operate with new sections on text interpreter.
 7035: 
 7036: @cindex immediate words
 7037: @cindex compile-only words
 7038: You can change the semantics of the most-recently defined word:
 7039: 
 7040: 
 7041: doc-immediate
 7042: doc-compile-only
 7043: doc-restrict
 7044: 
 7045: By convention, words with non-default compilation semantics (e.g.,
 7046: immediate words) often have names surrounded with brackets (e.g.,
 7047: @code{[']}, @pxref{Execution token}).
 7048: 
 7049: Note that ticking (@code{'}) a compile-only word gives an error
 7050: (``Interpreting a compile-only word'').
 7051: 
 7052: @menu
 7053: * Combined words::              
 7054: @end menu
 7055: 
 7056: 
 7057: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 7058: @subsection Combined Words
 7059: @cindex combined words
 7060: 
 7061: Gforth allows you to define @dfn{combined words} -- words that have an
 7062: arbitrary combination of interpretation and compilation semantics.
 7063: 
 7064: doc-interpret/compile:
 7065: 
 7066: This feature was introduced for implementing @code{TO} and @code{S"}. I
 7067: recommend that you do not define such words, as cute as they may be:
 7068: they make it hard to get at both parts of the word in some contexts.
 7069: E.g., assume you want to get an execution token for the compilation
 7070: part. Instead, define two words, one that embodies the interpretation
 7071: part, and one that embodies the compilation part.  Once you have done
 7072: that, you can define a combined word with @code{interpret/compile:} for
 7073: the convenience of your users.
 7074: 
 7075: You might try to use this feature to provide an optimizing
 7076: implementation of the default compilation semantics of a word. For
 7077: example, by defining:
 7078: @example
 7079: :noname
 7080:    foo bar ;
 7081: :noname
 7082:    POSTPONE foo POSTPONE bar ;
 7083: interpret/compile: opti-foobar
 7084: @end example
 7085: 
 7086: @noindent
 7087: as an optimizing version of:
 7088: 
 7089: @example
 7090: : foobar
 7091:     foo bar ;
 7092: @end example
 7093: 
 7094: Unfortunately, this does not work correctly with @code{[compile]},
 7095: because @code{[compile]} assumes that the compilation semantics of all
 7096: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 7097: opti-foobar} would compile compilation semantics, whereas
 7098: @code{[compile] foobar} would compile interpretation semantics.
 7099: 
 7100: @cindex state-smart words (are a bad idea)
 7101: @anchor{state-smartness}
 7102: Some people try to use @dfn{state-smart} words to emulate the feature provided
 7103: by @code{interpret/compile:} (words are state-smart if they check
 7104: @code{STATE} during execution). E.g., they would try to code
 7105: @code{foobar} like this:
 7106: 
 7107: @example
 7108: : foobar
 7109:   STATE @@
 7110:   IF ( compilation state )
 7111:     POSTPONE foo POSTPONE bar
 7112:   ELSE
 7113:     foo bar
 7114:   ENDIF ; immediate
 7115: @end example
 7116: 
 7117: Although this works if @code{foobar} is only processed by the text
 7118: interpreter, it does not work in other contexts (like @code{'} or
 7119: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 7120: for a state-smart word, not for the interpretation semantics of the
 7121: original @code{foobar}; when you execute this execution token (directly
 7122: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 7123: state, the result will not be what you expected (i.e., it will not
 7124: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 7125: write them@footnote{For a more detailed discussion of this topic, see
 7126: M. Anton Ertl,
 7127: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 7128: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 7129: 
 7130: @cindex defining words with arbitrary semantics combinations
 7131: It is also possible to write defining words that define words with
 7132: arbitrary combinations of interpretation and compilation semantics. In
 7133: general, they look like this:
 7134: 
 7135: @example
 7136: : def-word
 7137:     create-interpret/compile
 7138:     @i{code1}
 7139: interpretation>
 7140:     @i{code2}
 7141: <interpretation
 7142: compilation>
 7143:     @i{code3}
 7144: <compilation ;
 7145: @end example
 7146: 
 7147: For a @i{word} defined with @code{def-word}, the interpretation
 7148: semantics are to push the address of the body of @i{word} and perform
 7149: @i{code2}, and the compilation semantics are to push the address of
 7150: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 7151: can also be defined like this (except that the defined constants don't
 7152: behave correctly when @code{[compile]}d):
 7153: 
 7154: @example
 7155: : constant ( n "name" -- )
 7156:     create-interpret/compile
 7157:     ,
 7158: interpretation> ( -- n )
 7159:     @@
 7160: <interpretation
 7161: compilation> ( compilation. -- ; run-time. -- n )
 7162:     @@ postpone literal
 7163: <compilation ;
 7164: @end example
 7165: 
 7166: 
 7167: doc-create-interpret/compile
 7168: doc-interpretation>
 7169: doc-<interpretation
 7170: doc-compilation>
 7171: doc-<compilation
 7172: 
 7173: 
 7174: Words defined with @code{interpret/compile:} and
 7175: @code{create-interpret/compile} have an extended header structure that
 7176: differs from other words; however, unless you try to access them with
 7177: plain address arithmetic, you should not notice this. Words for
 7178: accessing the header structure usually know how to deal with this; e.g.,
 7179: @code{'} @i{word} @code{>body} also gives you the body of a word created
 7180: with @code{create-interpret/compile}.
 7181: 
 7182: 
 7183: @c -------------------------------------------------------------
 7184: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 7185: @section Tokens for Words
 7186: @cindex tokens for words
 7187: 
 7188: This section describes the creation and use of tokens that represent
 7189: words.
 7190: 
 7191: @menu
 7192: * Execution token::             represents execution/interpretation semantics
 7193: * Compilation token::           represents compilation semantics
 7194: * Name token::                  represents named words
 7195: @end menu
 7196: 
 7197: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 7198: @subsection Execution token
 7199: 
 7200: @cindex xt
 7201: @cindex execution token
 7202: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 7203: You can use @code{execute} to invoke this behaviour.
 7204: 
 7205: @cindex tick (')
 7206: You can use @code{'} to get an execution token that represents the
 7207: interpretation semantics of a named word:
 7208: 
 7209: @example
 7210: 5 ' .   ( n xt ) 
 7211: execute ( )      \ execute the xt (i.e., ".")
 7212: @end example
 7213: 
 7214: doc-'
 7215: 
 7216: @code{'} parses at run-time; there is also a word @code{[']} that parses
 7217: when it is compiled, and compiles the resulting XT:
 7218: 
 7219: @example
 7220: : foo ['] . execute ;
 7221: 5 foo
 7222: : bar ' execute ; \ by contrast,
 7223: 5 bar .           \ ' parses "." when bar executes
 7224: @end example
 7225: 
 7226: doc-[']
 7227: 
 7228: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7229: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7230: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7231: compile-only words (because these words have no interpretation
 7232: semantics).  You might get what you want by using @code{COMP' @i{word}
 7233: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7234: token}).
 7235: 
 7236: Another way to get an XT is @code{:noname} or @code{latestxt}
 7237: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7238: for the only behaviour the word has (the execution semantics).  For
 7239: named words, @code{latestxt} produces an XT for the same behaviour it
 7240: would produce if the word was defined anonymously.
 7241: 
 7242: @example
 7243: :noname ." hello" ;
 7244: execute
 7245: @end example
 7246: 
 7247: An XT occupies one cell and can be manipulated like any other cell.
 7248: 
 7249: @cindex code field address
 7250: @cindex CFA
 7251: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7252: operations that produce or consume it).  For old hands: In Gforth, the
 7253: XT is implemented as a code field address (CFA).
 7254: 
 7255: doc-execute
 7256: doc-perform
 7257: 
 7258: @node Compilation token, Name token, Execution token, Tokens for Words
 7259: @subsection Compilation token
 7260: 
 7261: @cindex compilation token
 7262: @cindex CT (compilation token)
 7263: Gforth represents the compilation semantics of a named word by a
 7264: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7265: @i{xt} is an execution token. The compilation semantics represented by
 7266: the compilation token can be performed with @code{execute}, which
 7267: consumes the whole compilation token, with an additional stack effect
 7268: determined by the represented compilation semantics.
 7269: 
 7270: At present, the @i{w} part of a compilation token is an execution token,
 7271: and the @i{xt} part represents either @code{execute} or
 7272: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7273: word. If the word has default compilation semantics, the @i{xt} will
 7274: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7275: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7276: knowledge, unless necessary; future versions of Gforth may introduce
 7277: unusual compilation tokens (e.g., a compilation token that represents
 7278: the compilation semantics of a literal).
 7279: 
 7280: You can perform the compilation semantics represented by the compilation
 7281: token with @code{execute}.  You can compile the compilation semantics
 7282: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7283: equivalent to @code{postpone @i{word}}.
 7284: 
 7285: doc-[comp']
 7286: doc-comp'
 7287: doc-postpone,
 7288: 
 7289: @node Name token,  , Compilation token, Tokens for Words
 7290: @subsection Name token
 7291: 
 7292: @cindex name token
 7293: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7294: token is an abstract data type that occurs as argument or result of the
 7295: words below.
 7296: 
 7297: @c !! put this elswhere?
 7298: @cindex name field address
 7299: @cindex NFA
 7300: The closest thing to the nt in older Forth systems is the name field
 7301: address (NFA), but there are significant differences: in older Forth
 7302: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7303: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7304: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7305: is a link field in the structure identified by the name token, but
 7306: searching usually uses a hash table external to these structures; the
 7307: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7308: implemented as the address of that count field.
 7309: 
 7310: doc-find-name
 7311: doc-latest
 7312: doc->name
 7313: doc-name>int
 7314: doc-name?int
 7315: doc-name>comp
 7316: doc-name>string
 7317: doc-id.
 7318: doc-.name
 7319: doc-.id
 7320: 
 7321: @c ----------------------------------------------------------
 7322: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7323: @section Compiling words
 7324: @cindex compiling words
 7325: @cindex macros
 7326: 
 7327: In contrast to most other languages, Forth has no strict boundary
 7328: between compilation and run-time.  E.g., you can run arbitrary code
 7329: between defining words (or for computing data used by defining words
 7330: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7331: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7332: running arbitrary code while compiling a colon definition (exception:
 7333: you must not allot dictionary space).
 7334: 
 7335: @menu
 7336: * Literals::                    Compiling data values
 7337: * Macros::                      Compiling words
 7338: @end menu
 7339: 
 7340: @node Literals, Macros, Compiling words, Compiling words
 7341: @subsection Literals
 7342: @cindex Literals
 7343: 
 7344: The simplest and most frequent example is to compute a literal during
 7345: compilation.  E.g., the following definition prints an array of strings,
 7346: one string per line:
 7347: 
 7348: @example
 7349: : .strings ( addr u -- ) \ gforth
 7350:     2* cells bounds U+DO
 7351: 	cr i 2@@ type
 7352:     2 cells +LOOP ;  
 7353: @end example
 7354: 
 7355: With a simple-minded compiler like Gforth's, this computes @code{2
 7356: cells} on every loop iteration.  You can compute this value once and for
 7357: all at compile time and compile it into the definition like this:
 7358: 
 7359: @example
 7360: : .strings ( addr u -- ) \ gforth
 7361:     2* cells bounds U+DO
 7362: 	cr i 2@@ type
 7363:     [ 2 cells ] literal +LOOP ;  
 7364: @end example
 7365: 
 7366: @code{[} switches the text interpreter to interpret state (you will get
 7367: an @code{ok} prompt if you type this example interactively and insert a
 7368: newline between @code{[} and @code{]}), so it performs the
 7369: interpretation semantics of @code{2 cells}; this computes a number.
 7370: @code{]} switches the text interpreter back into compile state.  It then
 7371: performs @code{Literal}'s compilation semantics, which are to compile
 7372: this number into the current word.  You can decompile the word with
 7373: @code{see .strings} to see the effect on the compiled code.
 7374: 
 7375: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7376: *} in this way.
 7377: 
 7378: doc-[
 7379: doc-]
 7380: doc-literal
 7381: doc-]L
 7382: 
 7383: There are also words for compiling other data types than single cells as
 7384: literals:
 7385: 
 7386: doc-2literal
 7387: doc-fliteral
 7388: doc-sliteral
 7389: 
 7390: @cindex colon-sys, passing data across @code{:}
 7391: @cindex @code{:}, passing data across
 7392: You might be tempted to pass data from outside a colon definition to the
 7393: inside on the data stack.  This does not work, because @code{:} puhes a
 7394: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7395: 
 7396: @example
 7397: 5 : foo literal ; \ error: "unstructured"
 7398: @end example
 7399: 
 7400: Instead, you have to pass the value in some other way, e.g., through a
 7401: variable:
 7402: 
 7403: @example
 7404: variable temp
 7405: 5 temp !
 7406: : foo [ temp @@ ] literal ;
 7407: @end example
 7408: 
 7409: 
 7410: @node Macros,  , Literals, Compiling words
 7411: @subsection Macros
 7412: @cindex Macros
 7413: @cindex compiling compilation semantics
 7414: 
 7415: @code{Literal} and friends compile data values into the current
 7416: definition.  You can also write words that compile other words into the
 7417: current definition.  E.g.,
 7418: 
 7419: @example
 7420: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7421:   POSTPONE + ;
 7422: 
 7423: : foo ( n1 n2 -- n )
 7424:   [ compile-+ ] ;
 7425: 1 2 foo .
 7426: @end example
 7427: 
 7428: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7429: What happens in this example?  @code{Postpone} compiles the compilation
 7430: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7431: executes @code{compile-+} and thus the compilation semantics of +, which
 7432: compile (the execution semantics of) @code{+} into
 7433: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7434: should only be executed in compile state, so this example is not
 7435: guaranteed to work on all standard systems, but on any decent system it
 7436: will work.}
 7437: 
 7438: doc-postpone
 7439: 
 7440: Compiling words like @code{compile-+} are usually immediate (or similar)
 7441: so you do not have to switch to interpret state to execute them;
 7442: modifying the last example accordingly produces:
 7443: 
 7444: @example
 7445: : [compile-+] ( compilation: --; interpretation: -- )
 7446:   \ compiled code: ( n1 n2 -- n )
 7447:   POSTPONE + ; immediate
 7448: 
 7449: : foo ( n1 n2 -- n )
 7450:   [compile-+] ;
 7451: 1 2 foo .
 7452: @end example
 7453: 
 7454: You will occassionally find the need to POSTPONE several words;
 7455: putting POSTPONE before each such word is cumbersome, so Gforth
 7456: provides a more convenient syntax: @code{]] ... [[}.  This
 7457: allows us to write @code{[compile-+]} as:
 7458: 
 7459: @example
 7460: : [compile-+] ( compilation: --; interpretation: -- )
 7461:   ]] + [[ ; immediate
 7462: @end example
 7463: 
 7464: doc-]]
 7465: doc-[[
 7466: 
 7467: The unusual direction of the brackets indicates their function:
 7468: @code{]]} switches from compilation to postponing (i.e., compilation
 7469: of compilation), just like @code{]} switches from immediate execution
 7470: (interpretation) to compilation.  Conversely, @code{[[} switches from
 7471: postponing to compilation, ananlogous to @code{[} which switches from
 7472: compilation to immediate execution.
 7473: 
 7474: The real advantage of @code{]] }...@code{ [[} becomes apparent when
 7475: there are many words to POSTPONE.  E.g., the word
 7476: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
 7477: written much shorter as follows:
 7478: 
 7479: @example
 7480: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 7481: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 7482: \ array beginning at addr and containing u elements
 7483:   @{ xt @}
 7484:   ]] cells over + swap ?do
 7485:     i @@ [[ xt compile, 
 7486:   1 cells ]]L +loop [[ ;
 7487: @end example
 7488: 
 7489: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
 7490: There are also other shortcuts
 7491: 
 7492: doc-]]L
 7493: doc-]]2L
 7494: doc-]]FL
 7495: doc-]]SL
 7496: 
 7497: Note that parsing words don't parse at postpone time; if you want to
 7498: provide the parsed string right away, you have to switch back to
 7499: compilation:
 7500: 
 7501: @example
 7502: ]] ... [[ s" some string" ]]2L ... [[
 7503: ]] ... [[ ['] + ]]L ... [[
 7504: @end example
 7505: 
 7506: Definitions of @code{]]} and friends in ANS Forth are provided in
 7507: @file{compat/macros.fs}.
 7508: 
 7509: Immediate compiling words are similar to macros in other languages (in
 7510: particular, Lisp).  The important differences to macros in, e.g., C are:
 7511: 
 7512: @itemize @bullet
 7513: 
 7514: @item
 7515: You use the same language for defining and processing macros, not a
 7516: separate preprocessing language and processor.
 7517: 
 7518: @item
 7519: Consequently, the full power of Forth is available in macro definitions.
 7520: E.g., you can perform arbitrarily complex computations, or generate
 7521: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7522: Tutorial}).  This power is very useful when writing a parser generators
 7523: or other code-generating software.
 7524: 
 7525: @item
 7526: Macros defined using @code{postpone} etc. deal with the language at a
 7527: higher level than strings; name binding happens at macro definition
 7528: time, so you can avoid the pitfalls of name collisions that can happen
 7529: in C macros.  Of course, Forth is a liberal language and also allows to
 7530: shoot yourself in the foot with text-interpreted macros like
 7531: 
 7532: @example
 7533: : [compile-+] s" +" evaluate ; immediate
 7534: @end example
 7535: 
 7536: Apart from binding the name at macro use time, using @code{evaluate}
 7537: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7538: @end itemize
 7539: 
 7540: You may want the macro to compile a number into a word.  The word to do
 7541: it is @code{literal}, but you have to @code{postpone} it, so its
 7542: compilation semantics take effect when the macro is executed, not when
 7543: it is compiled:
 7544: 
 7545: @example
 7546: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7547:   5 POSTPONE literal ; immediate
 7548: 
 7549: : foo [compile-5] ;
 7550: foo .
 7551: @end example
 7552: 
 7553: You may want to pass parameters to a macro, that the macro should
 7554: compile into the current definition.  If the parameter is a number, then
 7555: you can use @code{postpone literal} (similar for other values).
 7556: 
 7557: If you want to pass a word that is to be compiled, the usual way is to
 7558: pass an execution token and @code{compile,} it:
 7559: 
 7560: @example
 7561: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7562:   dup compile, compile, ;
 7563: 
 7564: : 2+ ( n1 -- n2 )
 7565:   [ ' 1+ twice1 ] ;
 7566: @end example
 7567: 
 7568: doc-compile,
 7569: 
 7570: An alternative available in Gforth, that allows you to pass compile-only
 7571: words as parameters is to use the compilation token (@pxref{Compilation
 7572: token}).  The same example in this technique:
 7573: 
 7574: @example
 7575: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7576:   2dup 2>r execute 2r> execute ;
 7577: 
 7578: : 2+ ( n1 -- n2 )
 7579:   [ comp' 1+ twice ] ;
 7580: @end example
 7581: 
 7582: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7583: works even if the executed compilation semantics has an effect on the
 7584: data stack.
 7585: 
 7586: You can also define complete definitions with these words; this provides
 7587: an alternative to using @code{does>} (@pxref{User-defined Defining
 7588: Words}).  E.g., instead of
 7589: 
 7590: @example
 7591: : curry+ ( n1 "name" -- )
 7592:     CREATE ,
 7593: DOES> ( n2 -- n1+n2 )
 7594:     @@ + ;
 7595: @end example
 7596: 
 7597: you could define
 7598: 
 7599: @example
 7600: : curry+ ( n1 "name" -- )
 7601:   \ name execution: ( n2 -- n1+n2 )
 7602:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7603: 
 7604: -3 curry+ 3-
 7605: see 3-
 7606: @end example
 7607: 
 7608: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7609: colon-sys on the data stack that makes everything below it unaccessible.
 7610: 
 7611: This way of writing defining words is sometimes more, sometimes less
 7612: convenient than using @code{does>} (@pxref{Advanced does> usage
 7613: example}).  One advantage of this method is that it can be optimized
 7614: better, because the compiler knows that the value compiled with
 7615: @code{literal} is fixed, whereas the data associated with a
 7616: @code{create}d word can be changed.
 7617: 
 7618: @c doc-[compile] !! not properly documented
 7619: 
 7620: @c ----------------------------------------------------------
 7621: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7622: @section  The Text Interpreter
 7623: @cindex interpreter - outer
 7624: @cindex text interpreter
 7625: @cindex outer interpreter
 7626: 
 7627: @c Should we really describe all these ugly details?  IMO the text
 7628: @c interpreter should be much cleaner, but that may not be possible within
 7629: @c ANS Forth. - anton
 7630: @c nac-> I wanted to explain how it works to show how you can exploit
 7631: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7632: @c some of these gory details was very helpful to me. None of the textbooks
 7633: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7634: @c seems to positively avoid going into too much detail for some of
 7635: @c the internals.
 7636: 
 7637: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7638: @c it is; for the ugly details, I would prefer another place.  I wonder
 7639: @c whether we should have a chapter before "Words" that describes some
 7640: @c basic concepts referred to in words, and a chapter after "Words" that
 7641: @c describes implementation details.
 7642: 
 7643: The text interpreter@footnote{This is an expanded version of the
 7644: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7645: that processes input from the current input device. It is also called
 7646: the outer interpreter, in contrast to the inner interpreter
 7647: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7648: implementations.
 7649: 
 7650: @cindex interpret state
 7651: @cindex compile state
 7652: The text interpreter operates in one of two states: @dfn{interpret
 7653: state} and @dfn{compile state}. The current state is defined by the
 7654: aptly-named variable @code{state}.
 7655: 
 7656: This section starts by describing how the text interpreter behaves when
 7657: it is in interpret state, processing input from the user input device --
 7658: the keyboard. This is the mode that a Forth system is in after it starts
 7659: up.
 7660: 
 7661: @cindex input buffer
 7662: @cindex terminal input buffer
 7663: The text interpreter works from an area of memory called the @dfn{input
 7664: buffer}@footnote{When the text interpreter is processing input from the
 7665: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7666: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7667: @code{#TIB}.}, which stores your keyboard input when you press the
 7668: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7669: leading spaces (called @dfn{delimiters}) then parses a string (a
 7670: sequence of non-space characters) until it reaches either a space
 7671: character or the end of the buffer. Having parsed a string, it makes two
 7672: attempts to process it:
 7673: 
 7674: @cindex dictionary
 7675: @itemize @bullet
 7676: @item
 7677: It looks for the string in a @dfn{dictionary} of definitions. If the
 7678: string is found, the string names a @dfn{definition} (also known as a
 7679: @dfn{word}) and the dictionary search returns information that allows
 7680: the text interpreter to perform the word's @dfn{interpretation
 7681: semantics}. In most cases, this simply means that the word will be
 7682: executed.
 7683: @item
 7684: If the string is not found in the dictionary, the text interpreter
 7685: attempts to treat it as a number, using the rules described in
 7686: @ref{Number Conversion}. If the string represents a legal number in the
 7687: current radix, the number is pushed onto a parameter stack (the data
 7688: stack for integers, the floating-point stack for floating-point
 7689: numbers).
 7690: @end itemize
 7691: 
 7692: If both attempts fail, or if the word is found in the dictionary but has
 7693: no interpretation semantics@footnote{This happens if the word was
 7694: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7695: remainder of the input buffer, issues an error message and waits for
 7696: more input. If one of the attempts succeeds, the text interpreter
 7697: repeats the parsing process until the whole of the input buffer has been
 7698: processed, at which point it prints the status message ``@code{ ok}''
 7699: and waits for more input.
 7700: 
 7701: @c anton: this should be in the input stream subsection (or below it)
 7702: 
 7703: @cindex parse area
 7704: The text interpreter keeps track of its position in the input buffer by
 7705: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7706: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7707: of the input buffer. The region from offset @code{>IN @@} to the end of
 7708: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7709: the text interpreter processes the contents of the input buffer by
 7710: parsing strings from the parse area until the parse area is empty.}.
 7711: This example shows how @code{>IN} changes as the text interpreter parses
 7712: the input buffer:
 7713: 
 7714: @example
 7715: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7716:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7717: 
 7718: 1 2 3 remaining + remaining . 
 7719: 
 7720: : foo 1 2 3 remaining SWAP remaining ;
 7721: @end example
 7722: 
 7723: @noindent
 7724: The result is:
 7725: 
 7726: @example
 7727: ->+ remaining .<-
 7728: ->.<-5  ok
 7729: 
 7730: ->SWAP remaining ;-<
 7731: ->;<-  ok
 7732: @end example
 7733: 
 7734: @cindex parsing words
 7735: The value of @code{>IN} can also be modified by a word in the input
 7736: buffer that is executed by the text interpreter.  This means that a word
 7737: can ``trick'' the text interpreter into either skipping a section of the
 7738: input buffer@footnote{This is how parsing words work.} or into parsing a
 7739: section twice. For example:
 7740: 
 7741: @example
 7742: : lat ." <<foo>>" ;
 7743: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7744: @end example
 7745: 
 7746: @noindent
 7747: When @code{flat} is executed, this output is produced@footnote{Exercise
 7748: for the reader: what would happen if the @code{3} were replaced with
 7749: @code{4}?}:
 7750: 
 7751: @example
 7752: <<bar>><<foo>>
 7753: @end example
 7754: 
 7755: This technique can be used to work around some of the interoperability
 7756: problems of parsing words.  Of course, it's better to avoid parsing
 7757: words where possible.
 7758: 
 7759: @noindent
 7760: Two important notes about the behaviour of the text interpreter:
 7761: 
 7762: @itemize @bullet
 7763: @item
 7764: It processes each input string to completion before parsing additional
 7765: characters from the input buffer.
 7766: @item
 7767: It treats the input buffer as a read-only region (and so must your code).
 7768: @end itemize
 7769: 
 7770: @noindent
 7771: When the text interpreter is in compile state, its behaviour changes in
 7772: these ways:
 7773: 
 7774: @itemize @bullet
 7775: @item
 7776: If a parsed string is found in the dictionary, the text interpreter will
 7777: perform the word's @dfn{compilation semantics}. In most cases, this
 7778: simply means that the execution semantics of the word will be appended
 7779: to the current definition.
 7780: @item
 7781: When a number is encountered, it is compiled into the current definition
 7782: (as a literal) rather than being pushed onto a parameter stack.
 7783: @item
 7784: If an error occurs, @code{state} is modified to put the text interpreter
 7785: back into interpret state.
 7786: @item
 7787: Each time a line is entered from the keyboard, Gforth prints
 7788: ``@code{ compiled}'' rather than `` @code{ok}''.
 7789: @end itemize
 7790: 
 7791: @cindex text interpreter - input sources
 7792: When the text interpreter is using an input device other than the
 7793: keyboard, its behaviour changes in these ways:
 7794: 
 7795: @itemize @bullet
 7796: @item
 7797: When the parse area is empty, the text interpreter attempts to refill
 7798: the input buffer from the input source. When the input source is
 7799: exhausted, the input source is set back to the previous input source.
 7800: @item
 7801: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7802: time the parse area is emptied.
 7803: @item
 7804: If an error occurs, the input source is set back to the user input
 7805: device.
 7806: @end itemize
 7807: 
 7808: You can read about this in more detail in @ref{Input Sources}.
 7809: 
 7810: doc->in
 7811: doc-source
 7812: 
 7813: doc-tib
 7814: doc-#tib
 7815: 
 7816: 
 7817: @menu
 7818: * Input Sources::               
 7819: * Number Conversion::           
 7820: * Interpret/Compile states::    
 7821: * Interpreter Directives::      
 7822: @end menu
 7823: 
 7824: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7825: @subsection Input Sources
 7826: @cindex input sources
 7827: @cindex text interpreter - input sources
 7828: 
 7829: By default, the text interpreter processes input from the user input
 7830: device (the keyboard) when Forth starts up. The text interpreter can
 7831: process input from any of these sources:
 7832: 
 7833: @itemize @bullet
 7834: @item
 7835: The user input device -- the keyboard.
 7836: @item
 7837: A file, using the words described in @ref{Forth source files}.
 7838: @item
 7839: A block, using the words described in @ref{Blocks}.
 7840: @item
 7841: A text string, using @code{evaluate}.
 7842: @end itemize
 7843: 
 7844: A program can identify the current input device from the values of
 7845: @code{source-id} and @code{blk}.
 7846: 
 7847: 
 7848: doc-source-id
 7849: doc-blk
 7850: 
 7851: doc-save-input
 7852: doc-restore-input
 7853: 
 7854: doc-evaluate
 7855: doc-query
 7856: 
 7857: 
 7858: 
 7859: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7860: @subsection Number Conversion
 7861: @cindex number conversion
 7862: @cindex double-cell numbers, input format
 7863: @cindex input format for double-cell numbers
 7864: @cindex single-cell numbers, input format
 7865: @cindex input format for single-cell numbers
 7866: @cindex floating-point numbers, input format
 7867: @cindex input format for floating-point numbers
 7868: 
 7869: This section describes the rules that the text interpreter uses when it
 7870: tries to convert a string into a number.
 7871: 
 7872: Let <digit> represent any character that is a legal digit in the current
 7873: number base@footnote{For example, 0-9 when the number base is decimal or
 7874: 0-9, A-F when the number base is hexadecimal.}.
 7875: 
 7876: Let <decimal digit> represent any character in the range 0-9.
 7877: 
 7878: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7879: in the braces (@i{a} or @i{b} or neither).
 7880: 
 7881: Let * represent any number of instances of the previous character
 7882: (including none).
 7883: 
 7884: Let any other character represent itself.
 7885: 
 7886: @noindent
 7887: Now, the conversion rules are:
 7888: 
 7889: @itemize @bullet
 7890: @item
 7891: A string of the form <digit><digit>* is treated as a single-precision
 7892: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7893: @item
 7894: A string of the form -<digit><digit>* is treated as a single-precision
 7895: (cell-sized) negative integer, and is represented using 2's-complement
 7896: arithmetic. Examples are -45 -5681 -0
 7897: @item
 7898: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7899: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7900: (all three of these represent the same number).
 7901: @item
 7902: A string of the form -<digit><digit>*.<digit>* is treated as a
 7903: double-precision (double-cell-sized) negative integer, and is
 7904: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7905: -34.65 (all three of these represent the same number).
 7906: @item
 7907: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7908: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7909: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7910: number) +12.E-4
 7911: @end itemize
 7912: 
 7913: By default, the number base used for integer number conversion is
 7914: given by the contents of the variable @code{base}.  Note that a lot of
 7915: confusion can result from unexpected values of @code{base}.  If you
 7916: change @code{base} anywhere, make sure to save the old value and
 7917: restore it afterwards; better yet, use @code{base-execute}, which does
 7918: this for you.  In general I recommend keeping @code{base} decimal, and
 7919: using the prefixes described below for the popular non-decimal bases.
 7920: 
 7921: doc-dpl
 7922: doc-base-execute
 7923: doc-base
 7924: doc-hex
 7925: doc-decimal
 7926: 
 7927: @cindex '-prefix for character strings
 7928: @cindex &-prefix for decimal numbers
 7929: @cindex #-prefix for decimal numbers
 7930: @cindex %-prefix for binary numbers
 7931: @cindex $-prefix for hexadecimal numbers
 7932: @cindex 0x-prefix for hexadecimal numbers
 7933: Gforth allows you to override the value of @code{base} by using a
 7934: prefix@footnote{Some Forth implementations provide a similar scheme by
 7935: implementing @code{$} etc. as parsing words that process the subsequent
 7936: number in the input stream and push it onto the stack. For example, see
 7937: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7938: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7939: is required between the prefix and the number.} before the first digit
 7940: of an (integer) number. The following prefixes are supported:
 7941: 
 7942: @itemize @bullet
 7943: @item
 7944: @code{&} -- decimal
 7945: @item
 7946: @code{#} -- decimal
 7947: @item
 7948: @code{%} -- binary
 7949: @item
 7950: @code{$} -- hexadecimal
 7951: @item
 7952: @code{0x} -- hexadecimal, if base<33.
 7953: @item
 7954: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 7955: optional @code{'} may be present after the character.
 7956: @end itemize
 7957: 
 7958: Here are some examples, with the equivalent decimal number shown after
 7959: in braces:
 7960: 
 7961: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7962: 'A (65),
 7963: -'a' (-97),
 7964: &905 (905), $abc (2478), $ABC (2478).
 7965: 
 7966: @cindex number conversion - traps for the unwary
 7967: @noindent
 7968: Number conversion has a number of traps for the unwary:
 7969: 
 7970: @itemize @bullet
 7971: @item
 7972: You cannot determine the current number base using the code sequence
 7973: @code{base @@ .} -- the number base is always 10 in the current number
 7974: base. Instead, use something like @code{base @@ dec.}
 7975: @item
 7976: If the number base is set to a value greater than 14 (for example,
 7977: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7978: it to be intepreted as either a single-precision integer or a
 7979: floating-point number (Gforth treats it as an integer). The ambiguity
 7980: can be resolved by explicitly stating the sign of the mantissa and/or
 7981: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7982: ambiguity arises; either representation will be treated as a
 7983: floating-point number.
 7984: @item
 7985: There is a word @code{bin} but it does @i{not} set the number base!
 7986: It is used to specify file types.
 7987: @item
 7988: ANS Forth requires the @code{.} of a double-precision number to be the
 7989: final character in the string.  Gforth allows the @code{.} to be
 7990: anywhere after the first digit.
 7991: @item
 7992: The number conversion process does not check for overflow.
 7993: @item
 7994: In an ANS Forth program @code{base} is required to be decimal when
 7995: converting floating-point numbers.  In Gforth, number conversion to
 7996: floating-point numbers always uses base &10, irrespective of the value
 7997: of @code{base}.
 7998: @end itemize
 7999: 
 8000: You can read numbers into your programs with the words described in
 8001: @ref{Line input and conversion}.
 8002: 
 8003: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 8004: @subsection Interpret/Compile states
 8005: @cindex Interpret/Compile states
 8006: 
 8007: A standard program is not permitted to change @code{state}
 8008: explicitly. However, it can change @code{state} implicitly, using the
 8009: words @code{[} and @code{]}. When @code{[} is executed it switches
 8010: @code{state} to interpret state, and therefore the text interpreter
 8011: starts interpreting. When @code{]} is executed it switches @code{state}
 8012: to compile state and therefore the text interpreter starts
 8013: compiling. The most common usage for these words is for switching into
 8014: interpret state and back from within a colon definition; this technique
 8015: can be used to compile a literal (for an example, @pxref{Literals}) or
 8016: for conditional compilation (for an example, @pxref{Interpreter
 8017: Directives}).
 8018: 
 8019: 
 8020: @c This is a bad example: It's non-standard, and it's not necessary.
 8021: @c However, I can't think of a good example for switching into compile
 8022: @c state when there is no current word (@code{state}-smart words are not a
 8023: @c good reason).  So maybe we should use an example for switching into
 8024: @c interpret @code{state} in a colon def. - anton
 8025: @c nac-> I agree. I started out by putting in the example, then realised
 8026: @c that it was non-ANS, so wrote more words around it. I hope this
 8027: @c re-written version is acceptable to you. I do want to keep the example
 8028: @c as it is helpful for showing what is and what is not portable, particularly
 8029: @c where it outlaws a style in common use.
 8030: 
 8031: @c anton: it's more important to show what's portable.  After we have done
 8032: @c that, we can also show what's not.  In any case, I have written a
 8033: @c section Compiling Words which also deals with [ ].
 8034: 
 8035: @c  !! The following example does not work in Gforth 0.5.9 or later.
 8036: 
 8037: @c  @code{[} and @code{]} also give you the ability to switch into compile
 8038: @c  state and back, but we cannot think of any useful Standard application
 8039: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 8040: 
 8041: @c  @example
 8042: @c  : AA ." this is A" ;
 8043: @c  : BB ." this is B" ;
 8044: @c  : CC ." this is C" ;
 8045: 
 8046: @c  create table ] aa bb cc [
 8047: 
 8048: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 8049: @c    cells table + @@ execute ;
 8050: @c  @end example
 8051: 
 8052: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 8053: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 8054: @c  defining @code{table} like this:
 8055: 
 8056: @c  @example
 8057: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 8058: @c  @end example
 8059: 
 8060: @c  The problem with this code is that the definition of @code{table} is not
 8061: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 8062: @c  @i{may} work on systems where code space and data space co-incide, the
 8063: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 8064: @c  word. In addition, the Standard only allows @code{@@} to access data
 8065: @c  space, whilst this example is using it to access code space. The only
 8066: @c  portable, Standard way to build this table is to build it in data space,
 8067: @c  like this:
 8068: 
 8069: @c  @example
 8070: @c  create table ' aa , ' bb , ' cc ,
 8071: @c  @end example
 8072: 
 8073: @c  doc-state
 8074: 
 8075: 
 8076: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 8077: @subsection Interpreter Directives
 8078: @cindex interpreter directives
 8079: @cindex conditional compilation
 8080: 
 8081: These words are usually used in interpret state; typically to control
 8082: which parts of a source file are processed by the text
 8083: interpreter. There are only a few ANS Forth Standard words, but Gforth
 8084: supplements these with a rich set of immediate control structure words
 8085: to compensate for the fact that the non-immediate versions can only be
 8086: used in compile state (@pxref{Control Structures}). Typical usages:
 8087: 
 8088: @example
 8089: FALSE Constant HAVE-ASSEMBLER
 8090: .
 8091: .
 8092: HAVE-ASSEMBLER [IF]
 8093: : ASSEMBLER-FEATURE
 8094:   ...
 8095: ;
 8096: [ENDIF]
 8097: .
 8098: .
 8099: : SEE
 8100:   ... \ general-purpose SEE code
 8101:   [ HAVE-ASSEMBLER [IF] ]
 8102:   ... \ assembler-specific SEE code
 8103:   [ [ENDIF] ]
 8104: ;
 8105: @end example
 8106: 
 8107: 
 8108: doc-[IF]
 8109: doc-[ELSE]
 8110: doc-[THEN]
 8111: doc-[ENDIF]
 8112: 
 8113: doc-[IFDEF]
 8114: doc-[IFUNDEF]
 8115: 
 8116: doc-[?DO]
 8117: doc-[DO]
 8118: doc-[FOR]
 8119: doc-[LOOP]
 8120: doc-[+LOOP]
 8121: doc-[NEXT]
 8122: 
 8123: doc-[BEGIN]
 8124: doc-[UNTIL]
 8125: doc-[AGAIN]
 8126: doc-[WHILE]
 8127: doc-[REPEAT]
 8128: 
 8129: 
 8130: @c -------------------------------------------------------------
 8131: @node The Input Stream, Word Lists, The Text Interpreter, Words
 8132: @section The Input Stream
 8133: @cindex input stream
 8134: 
 8135: @c !! integrate this better with the "Text Interpreter" section
 8136: The text interpreter reads from the input stream, which can come from
 8137: several sources (@pxref{Input Sources}).  Some words, in particular
 8138: defining words, but also words like @code{'}, read parameters from the
 8139: input stream instead of from the stack.
 8140: 
 8141: Such words are called parsing words, because they parse the input
 8142: stream.  Parsing words are hard to use in other words, because it is
 8143: hard to pass program-generated parameters through the input stream.
 8144: They also usually have an unintuitive combination of interpretation and
 8145: compilation semantics when implemented naively, leading to various
 8146: approaches that try to produce a more intuitive behaviour
 8147: (@pxref{Combined words}).
 8148: 
 8149: It should be obvious by now that parsing words are a bad idea.  If you
 8150: want to implement a parsing word for convenience, also provide a factor
 8151: of the word that does not parse, but takes the parameters on the stack.
 8152: To implement the parsing word on top if it, you can use the following
 8153: words:
 8154: 
 8155: @c anton: these belong in the input stream section
 8156: doc-parse
 8157: doc-parse-name
 8158: doc-parse-word
 8159: doc-name
 8160: doc-word
 8161: doc-refill
 8162: 
 8163: Conversely, if you have the bad luck (or lack of foresight) to have to
 8164: deal with parsing words without having such factors, how do you pass a
 8165: string that is not in the input stream to it?
 8166: 
 8167: doc-execute-parsing
 8168: 
 8169: A definition of this word in ANS Forth is provided in
 8170: @file{compat/execute-parsing.fs}.
 8171: 
 8172: If you want to run a parsing word on a file, the following word should
 8173: help:
 8174: 
 8175: doc-execute-parsing-file
 8176: 
 8177: @c -------------------------------------------------------------
 8178: @node Word Lists, Environmental Queries, The Input Stream, Words
 8179: @section Word Lists
 8180: @cindex word lists
 8181: @cindex header space
 8182: 
 8183: A wordlist is a list of named words; you can add new words and look up
 8184: words by name (and you can remove words in a restricted way with
 8185: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 8186: 
 8187: @cindex search order stack
 8188: The text interpreter searches the wordlists present in the search order
 8189: (a stack of wordlists), from the top to the bottom.  Within each
 8190: wordlist, the search starts conceptually at the newest word; i.e., if
 8191: two words in a wordlist have the same name, the newer word is found.
 8192: 
 8193: @cindex compilation word list
 8194: New words are added to the @dfn{compilation wordlist} (aka current
 8195: wordlist).
 8196: 
 8197: @cindex wid
 8198: A word list is identified by a cell-sized word list identifier (@i{wid})
 8199: in much the same way as a file is identified by a file handle. The
 8200: numerical value of the wid has no (portable) meaning, and might change
 8201: from session to session.
 8202: 
 8203: The ANS Forth ``Search order'' word set is intended to provide a set of
 8204: low-level tools that allow various different schemes to be
 8205: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 8206: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 8207: Forth.
 8208: 
 8209: @comment TODO: locals section refers to here, saying that every word list (aka
 8210: @comment vocabulary) has its own methods for searching etc. Need to document that.
 8211: @c anton: but better in a separate subsection on wordlist internals
 8212: 
 8213: @comment TODO: document markers, reveal, tables, mappedwordlist
 8214: 
 8215: @comment the gforthman- prefix is used to pick out the true definition of a
 8216: @comment word from the source files, rather than some alias.
 8217: 
 8218: doc-forth-wordlist
 8219: doc-definitions
 8220: doc-get-current
 8221: doc-set-current
 8222: doc-get-order
 8223: doc-set-order
 8224: doc-wordlist
 8225: doc-table
 8226: doc->order
 8227: doc-previous
 8228: doc-also
 8229: doc-forth
 8230: doc-only
 8231: doc-order
 8232: 
 8233: doc-find
 8234: doc-search-wordlist
 8235: 
 8236: doc-words
 8237: doc-vlist
 8238: @c doc-words-deferred
 8239: 
 8240: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 8241: doc-root
 8242: doc-vocabulary
 8243: doc-seal
 8244: doc-vocs
 8245: doc-current
 8246: doc-context
 8247: 
 8248: 
 8249: @menu
 8250: * Vocabularies::                
 8251: * Why use word lists?::         
 8252: * Word list example::           
 8253: @end menu
 8254: 
 8255: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 8256: @subsection Vocabularies
 8257: @cindex Vocabularies, detailed explanation
 8258: 
 8259: Here is an example of creating and using a new wordlist using ANS
 8260: Forth words:
 8261: 
 8262: @example
 8263: wordlist constant my-new-words-wordlist
 8264: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 8265: 
 8266: \ add it to the search order
 8267: also my-new-words
 8268: 
 8269: \ alternatively, add it to the search order and make it
 8270: \ the compilation word list
 8271: also my-new-words definitions
 8272: \ type "order" to see the problem
 8273: @end example
 8274: 
 8275: The problem with this example is that @code{order} has no way to
 8276: associate the name @code{my-new-words} with the wid of the word list (in
 8277: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 8278: that has no associated name). There is no Standard way of associating a
 8279: name with a wid.
 8280: 
 8281: In Gforth, this example can be re-coded using @code{vocabulary}, which
 8282: associates a name with a wid:
 8283: 
 8284: @example
 8285: vocabulary my-new-words
 8286: 
 8287: \ add it to the search order
 8288: also my-new-words
 8289: 
 8290: \ alternatively, add it to the search order and make it
 8291: \ the compilation word list
 8292: my-new-words definitions
 8293: \ type "order" to see that the problem is solved
 8294: @end example
 8295: 
 8296: 
 8297: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8298: @subsection Why use word lists?
 8299: @cindex word lists - why use them?
 8300: 
 8301: Here are some reasons why people use wordlists:
 8302: 
 8303: @itemize @bullet
 8304: 
 8305: @c anton: Gforth's hashing implementation makes the search speed
 8306: @c independent from the number of words.  But it is linear with the number
 8307: @c of wordlists that have to be searched, so in effect using more wordlists
 8308: @c actually slows down compilation.
 8309: 
 8310: @c @item
 8311: @c To improve compilation speed by reducing the number of header space
 8312: @c entries that must be searched. This is achieved by creating a new
 8313: @c word list that contains all of the definitions that are used in the
 8314: @c definition of a Forth system but which would not usually be used by
 8315: @c programs running on that system. That word list would be on the search
 8316: @c list when the Forth system was compiled but would be removed from the
 8317: @c search list for normal operation. This can be a useful technique for
 8318: @c low-performance systems (for example, 8-bit processors in embedded
 8319: @c systems) but is unlikely to be necessary in high-performance desktop
 8320: @c systems.
 8321: 
 8322: @item
 8323: To prevent a set of words from being used outside the context in which
 8324: they are valid. Two classic examples of this are an integrated editor
 8325: (all of the edit commands are defined in a separate word list; the
 8326: search order is set to the editor word list when the editor is invoked;
 8327: the old search order is restored when the editor is terminated) and an
 8328: integrated assembler (the op-codes for the machine are defined in a
 8329: separate word list which is used when a @code{CODE} word is defined).
 8330: 
 8331: @item
 8332: To organize the words of an application or library into a user-visible
 8333: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8334: of helper words used just for the implementation (hidden in a separate
 8335: wordlist).  This keeps @code{words}' output smaller, separates
 8336: implementation and interface, and reduces the chance of name conflicts
 8337: within the common wordlist.
 8338: 
 8339: @item
 8340: To prevent a name-space clash between multiple definitions with the same
 8341: name. For example, when building a cross-compiler you might have a word
 8342: @code{IF} that generates conditional code for your target system. By
 8343: placing this definition in a different word list you can control whether
 8344: the host system's @code{IF} or the target system's @code{IF} get used in
 8345: any particular context by controlling the order of the word lists on the
 8346: search order stack.
 8347: 
 8348: @end itemize
 8349: 
 8350: The downsides of using wordlists are:
 8351: 
 8352: @itemize
 8353: 
 8354: @item
 8355: Debugging becomes more cumbersome.
 8356: 
 8357: @item
 8358: Name conflicts worked around with wordlists are still there, and you
 8359: have to arrange the search order carefully to get the desired results;
 8360: if you forget to do that, you get hard-to-find errors (as in any case
 8361: where you read the code differently from the compiler; @code{see} can
 8362: help seeing which of several possible words the name resolves to in such
 8363: cases).  @code{See} displays just the name of the words, not what
 8364: wordlist they belong to, so it might be misleading.  Using unique names
 8365: is a better approach to avoid name conflicts.
 8366: 
 8367: @item
 8368: You have to explicitly undo any changes to the search order.  In many
 8369: cases it would be more convenient if this happened implicitly.  Gforth
 8370: currently does not provide such a feature, but it may do so in the
 8371: future.
 8372: @end itemize
 8373: 
 8374: 
 8375: @node Word list example,  , Why use word lists?, Word Lists
 8376: @subsection Word list example
 8377: @cindex word lists - example
 8378: 
 8379: The following example is from the
 8380: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8381: garbage collector} and uses wordlists to separate public words from
 8382: helper words:
 8383: 
 8384: @example
 8385: get-current ( wid )
 8386: vocabulary garbage-collector also garbage-collector definitions
 8387: ... \ define helper words
 8388: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8389: ... \ define the public (i.e., API) words
 8390:     \ they can refer to the helper words
 8391: previous \ restore original search order (helper words become invisible)
 8392: @end example
 8393: 
 8394: @c -------------------------------------------------------------
 8395: @node Environmental Queries, Files, Word Lists, Words
 8396: @section Environmental Queries
 8397: @cindex environmental queries
 8398: 
 8399: ANS Forth introduced the idea of ``environmental queries'' as a way
 8400: for a program running on a system to determine certain characteristics of the system.
 8401: The Standard specifies a number of strings that might be recognised by a system.
 8402: 
 8403: The Standard requires that the header space used for environmental queries
 8404: be distinct from the header space used for definitions.
 8405: 
 8406: Typically, environmental queries are supported by creating a set of
 8407: definitions in a word list that is @i{only} used during environmental
 8408: queries; that is what Gforth does. There is no Standard way of adding
 8409: definitions to the set of recognised environmental queries, but any
 8410: implementation that supports the loading of optional word sets must have
 8411: some mechanism for doing this (after loading the word set, the
 8412: associated environmental query string must return @code{true}). In
 8413: Gforth, the word list used to honour environmental queries can be
 8414: manipulated just like any other word list.
 8415: 
 8416: 
 8417: doc-environment?
 8418: doc-environment-wordlist
 8419: 
 8420: doc-gforth
 8421: doc-os-class
 8422: 
 8423: 
 8424: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8425: returning two items on the stack, querying it using @code{environment?}
 8426: will return an additional item; the @code{true} flag that shows that the
 8427: string was recognised.
 8428: 
 8429: @comment TODO Document the standard strings or note where they are documented herein
 8430: 
 8431: Here are some examples of using environmental queries:
 8432: 
 8433: @example
 8434: s" address-unit-bits" environment? 0=
 8435: [IF]
 8436:      cr .( environmental attribute address-units-bits unknown... ) cr
 8437: [ELSE]
 8438:      drop \ ensure balanced stack effect
 8439: [THEN]
 8440: 
 8441: \ this might occur in the prelude of a standard program that uses THROW
 8442: s" exception" environment? [IF]
 8443:    0= [IF]
 8444:       : throw abort" exception thrown" ;
 8445:    [THEN]
 8446: [ELSE] \ we don't know, so make sure
 8447:    : throw abort" exception thrown" ;
 8448: [THEN]
 8449: 
 8450: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8451:                         [ELSE] .( Not Gforth..) [THEN]
 8452: 
 8453: \ a program using v*
 8454: s" gforth" environment? [IF]
 8455:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8456:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8457:      >r swap 2swap swap 0e r> 0 ?DO
 8458:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 8459:      LOOP
 8460:      2drop 2drop ; 
 8461:   [THEN]
 8462: [ELSE] \ 
 8463:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8464:   ...
 8465: [THEN]
 8466: @end example
 8467: 
 8468: Here is an example of adding a definition to the environment word list:
 8469: 
 8470: @example
 8471: get-current environment-wordlist set-current
 8472: true constant block
 8473: true constant block-ext
 8474: set-current
 8475: @end example
 8476: 
 8477: You can see what definitions are in the environment word list like this:
 8478: 
 8479: @example
 8480: environment-wordlist >order words previous
 8481: @end example
 8482: 
 8483: 
 8484: @c -------------------------------------------------------------
 8485: @node Files, Blocks, Environmental Queries, Words
 8486: @section Files
 8487: @cindex files
 8488: @cindex I/O - file-handling
 8489: 
 8490: Gforth provides facilities for accessing files that are stored in the
 8491: host operating system's file-system. Files that are processed by Gforth
 8492: can be divided into two categories:
 8493: 
 8494: @itemize @bullet
 8495: @item
 8496: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8497: @item
 8498: Files that are processed by some other program (@dfn{general files}).
 8499: @end itemize
 8500: 
 8501: @menu
 8502: * Forth source files::          
 8503: * General files::               
 8504: * Redirection::                 
 8505: * Search Paths::                
 8506: @end menu
 8507: 
 8508: @c -------------------------------------------------------------
 8509: @node Forth source files, General files, Files, Files
 8510: @subsection Forth source files
 8511: @cindex including files
 8512: @cindex Forth source files
 8513: 
 8514: The simplest way to interpret the contents of a file is to use one of
 8515: these two formats:
 8516: 
 8517: @example
 8518: include mysource.fs
 8519: s" mysource.fs" included
 8520: @end example
 8521: 
 8522: You usually want to include a file only if it is not included already
 8523: (by, say, another source file). In that case, you can use one of these
 8524: three formats:
 8525: 
 8526: @example
 8527: require mysource.fs
 8528: needs mysource.fs
 8529: s" mysource.fs" required
 8530: @end example
 8531: 
 8532: @cindex stack effect of included files
 8533: @cindex including files, stack effect
 8534: It is good practice to write your source files such that interpreting them
 8535: does not change the stack. Source files designed in this way can be used with
 8536: @code{required} and friends without complications. For example:
 8537: 
 8538: @example
 8539: 1024 require foo.fs drop
 8540: @end example
 8541: 
 8542: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8543: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8544: ), which allows its use with @code{require}.  Of course with such
 8545: parameters to required files, you have to ensure that the first
 8546: @code{require} fits for all uses (i.e., @code{require} it early in the
 8547: master load file).
 8548: 
 8549: doc-include-file
 8550: doc-included
 8551: doc-included?
 8552: doc-include
 8553: doc-required
 8554: doc-require
 8555: doc-needs
 8556: @c doc-init-included-files @c internal
 8557: doc-sourcefilename
 8558: doc-sourceline#
 8559: 
 8560: A definition in ANS Forth for @code{required} is provided in
 8561: @file{compat/required.fs}.
 8562: 
 8563: @c -------------------------------------------------------------
 8564: @node General files, Redirection, Forth source files, Files
 8565: @subsection General files
 8566: @cindex general files
 8567: @cindex file-handling
 8568: 
 8569: Files are opened/created by name and type. The following file access
 8570: methods (FAMs) are recognised:
 8571: 
 8572: @cindex fam (file access method)
 8573: doc-r/o
 8574: doc-r/w
 8575: doc-w/o
 8576: doc-bin
 8577: 
 8578: 
 8579: When a file is opened/created, it returns a file identifier,
 8580: @i{wfileid} that is used for all other file commands. All file
 8581: commands also return a status value, @i{wior}, that is 0 for a
 8582: successful operation and an implementation-defined non-zero value in the
 8583: case of an error.
 8584: 
 8585: 
 8586: doc-open-file
 8587: doc-create-file
 8588: 
 8589: doc-close-file
 8590: doc-delete-file
 8591: doc-rename-file
 8592: doc-read-file
 8593: doc-read-line
 8594: doc-key-file
 8595: doc-key?-file
 8596: doc-write-file
 8597: doc-write-line
 8598: doc-emit-file
 8599: doc-flush-file
 8600: 
 8601: doc-file-status
 8602: doc-file-position
 8603: doc-reposition-file
 8604: doc-file-size
 8605: doc-resize-file
 8606: 
 8607: doc-slurp-file
 8608: doc-slurp-fid
 8609: doc-stdin
 8610: doc-stdout
 8611: doc-stderr
 8612: 
 8613: @c ---------------------------------------------------------
 8614: @node Redirection, Search Paths, General files, Files
 8615: @subsection Redirection
 8616: @cindex Redirection
 8617: @cindex Input Redirection
 8618: @cindex Output Redirection
 8619: 
 8620: You can redirect the output of @code{type} and @code{emit} and all the
 8621: words that use them (all output words that don't have an explicit
 8622: target file) to an arbitrary file with the @code{outfile-execute},
 8623: used like this:
 8624: 
 8625: @example
 8626: : some-warning ( n -- )
 8627:     cr ." warning# " . ;
 8628: 
 8629: : print-some-warning ( n -- )
 8630:     ['] some-warning stderr outfile-execute ;
 8631: @end example
 8632: 
 8633: After @code{some-warning} is executed, the original output direction
 8634: is restored; this construct is safe against exceptions.  Similarly,
 8635: there is @code{infile-execute} for redirecting the input of @code{key}
 8636: and its users (any input word that does not take a file explicitly).
 8637: 
 8638: doc-outfile-execute
 8639: doc-infile-execute
 8640: 
 8641: If you do not want to redirect the input or output to a file, you can
 8642: also make use of the fact that @code{key}, @code{emit} and @code{type}
 8643: are deferred words (@pxref{Deferred Words}).  However, in that case
 8644: you have to worry about the restoration and the protection against
 8645: exceptions yourself; also, note that for redirecting the output in
 8646: this way, you have to redirect both @code{emit} and @code{type}.
 8647: 
 8648: @c ---------------------------------------------------------
 8649: @node Search Paths,  , Redirection, Files
 8650: @subsection Search Paths
 8651: @cindex path for @code{included}
 8652: @cindex file search path
 8653: @cindex @code{include} search path
 8654: @cindex search path for files
 8655: 
 8656: If you specify an absolute filename (i.e., a filename starting with
 8657: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8658: @samp{C:...})) for @code{included} and friends, that file is included
 8659: just as you would expect.
 8660: 
 8661: If the filename starts with @file{./}, this refers to the directory that
 8662: the present file was @code{included} from.  This allows files to include
 8663: other files relative to their own position (irrespective of the current
 8664: working directory or the absolute position).  This feature is essential
 8665: for libraries consisting of several files, where a file may include
 8666: other files from the library.  It corresponds to @code{#include "..."}
 8667: in C. If the current input source is not a file, @file{.} refers to the
 8668: directory of the innermost file being included, or, if there is no file
 8669: being included, to the current working directory.
 8670: 
 8671: For relative filenames (not starting with @file{./}), Gforth uses a
 8672: search path similar to Forth's search order (@pxref{Word Lists}). It
 8673: tries to find the given filename in the directories present in the path,
 8674: and includes the first one it finds. There are separate search paths for
 8675: Forth source files and general files.  If the search path contains the
 8676: directory @file{.}, this refers to the directory of the current file, or
 8677: the working directory, as if the file had been specified with @file{./}.
 8678: 
 8679: Use @file{~+} to refer to the current working directory (as in the
 8680: @code{bash}).
 8681: 
 8682: @c anton: fold the following subsubsections into this subsection?
 8683: 
 8684: @menu
 8685: * Source Search Paths::         
 8686: * General Search Paths::        
 8687: @end menu
 8688: 
 8689: @c ---------------------------------------------------------
 8690: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8691: @subsubsection Source Search Paths
 8692: @cindex search path control, source files
 8693: 
 8694: The search path is initialized when you start Gforth (@pxref{Invoking
 8695: Gforth}). You can display it and change it using @code{fpath} in
 8696: combination with the general path handling words.
 8697: 
 8698: doc-fpath
 8699: @c the functionality of the following words is easily available through
 8700: @c   fpath and the general path words.  The may go away.
 8701: @c doc-.fpath
 8702: @c doc-fpath+
 8703: @c doc-fpath=
 8704: @c doc-open-fpath-file
 8705: 
 8706: @noindent
 8707: Here is an example of using @code{fpath} and @code{require}:
 8708: 
 8709: @example
 8710: fpath path= /usr/lib/forth/|./
 8711: require timer.fs
 8712: @end example
 8713: 
 8714: 
 8715: @c ---------------------------------------------------------
 8716: @node General Search Paths,  , Source Search Paths, Search Paths
 8717: @subsubsection General Search Paths
 8718: @cindex search path control, source files
 8719: 
 8720: Your application may need to search files in several directories, like
 8721: @code{included} does. To facilitate this, Gforth allows you to define
 8722: and use your own search paths, by providing generic equivalents of the
 8723: Forth search path words:
 8724: 
 8725: doc-open-path-file
 8726: doc-path-allot
 8727: doc-clear-path
 8728: doc-also-path
 8729: doc-.path
 8730: doc-path+
 8731: doc-path=
 8732: 
 8733: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8734: 
 8735: Here's an example of creating an empty search path:
 8736: @c
 8737: @example
 8738: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8739: @end example
 8740: 
 8741: @c -------------------------------------------------------------
 8742: @node Blocks, Other I/O, Files, Words
 8743: @section Blocks
 8744: @cindex I/O - blocks
 8745: @cindex blocks
 8746: 
 8747: When you run Gforth on a modern desk-top computer, it runs under the
 8748: control of an operating system which provides certain services.  One of
 8749: these services is @var{file services}, which allows Forth source code
 8750: and data to be stored in files and read into Gforth (@pxref{Files}).
 8751: 
 8752: Traditionally, Forth has been an important programming language on
 8753: systems where it has interfaced directly to the underlying hardware with
 8754: no intervening operating system. Forth provides a mechanism, called
 8755: @dfn{blocks}, for accessing mass storage on such systems.
 8756: 
 8757: A block is a 1024-byte data area, which can be used to hold data or
 8758: Forth source code. No structure is imposed on the contents of the
 8759: block. A block is identified by its number; blocks are numbered
 8760: contiguously from 1 to an implementation-defined maximum.
 8761: 
 8762: A typical system that used blocks but no operating system might use a
 8763: single floppy-disk drive for mass storage, with the disks formatted to
 8764: provide 256-byte sectors. Blocks would be implemented by assigning the
 8765: first four sectors of the disk to block 1, the second four sectors to
 8766: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8767: would not contain any file system information, just the set of blocks.
 8768: 
 8769: @cindex blocks file
 8770: On systems that do provide file services, blocks are typically
 8771: implemented by storing a sequence of blocks within a single @dfn{blocks
 8772: file}.  The size of the blocks file will be an exact multiple of 1024
 8773: bytes, corresponding to the number of blocks it contains. This is the
 8774: mechanism that Gforth uses.
 8775: 
 8776: @cindex @file{blocks.fb}
 8777: Only one blocks file can be open at a time. If you use block words without
 8778: having specified a blocks file, Gforth defaults to the blocks file
 8779: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8780: locate a blocks file (@pxref{Source Search Paths}).
 8781: 
 8782: @cindex block buffers
 8783: When you read and write blocks under program control, Gforth uses a
 8784: number of @dfn{block buffers} as intermediate storage. These buffers are
 8785: not used when you use @code{load} to interpret the contents of a block.
 8786: 
 8787: The behaviour of the block buffers is analagous to that of a cache.
 8788: Each block buffer has three states:
 8789: 
 8790: @itemize @bullet
 8791: @item
 8792: Unassigned
 8793: @item
 8794: Assigned-clean
 8795: @item
 8796: Assigned-dirty
 8797: @end itemize
 8798: 
 8799: Initially, all block buffers are @i{unassigned}. In order to access a
 8800: block, the block (specified by its block number) must be assigned to a
 8801: block buffer.
 8802: 
 8803: The assignment of a block to a block buffer is performed by @code{block}
 8804: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8805: contents of a block. Use @code{buffer} when you don't care about the
 8806: existing contents of the block@footnote{The ANS Forth definition of
 8807: @code{buffer} is intended not to cause disk I/O; if the data associated
 8808: with the particular block is already stored in a block buffer due to an
 8809: earlier @code{block} command, @code{buffer} will return that block
 8810: buffer and the existing contents of the block will be
 8811: available. Otherwise, @code{buffer} will simply assign a new, empty
 8812: block buffer for the block.}.
 8813: 
 8814: Once a block has been assigned to a block buffer using @code{block} or
 8815: @code{buffer}, that block buffer becomes the @i{current block
 8816: buffer}. Data may only be manipulated (read or written) within the
 8817: current block buffer.
 8818: 
 8819: When the contents of the current block buffer has been modified it is
 8820: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8821: either abandon the changes (by doing nothing) or mark the block as
 8822: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8823: not change the blocks file; it simply changes a block buffer's state to
 8824: @i{assigned-dirty}.  The block will be written implicitly when it's
 8825: buffer is needed for another block, or explicitly by @code{flush} or
 8826: @code{save-buffers}.
 8827: 
 8828: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8829: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8830: @code{flush}.
 8831: 
 8832: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8833: algorithm to assign a block buffer to a block. That means that any
 8834: particular block can only be assigned to one specific block buffer,
 8835: called (for the particular operation) the @i{victim buffer}. If the
 8836: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8837: the new block immediately. If it is @i{assigned-dirty} its current
 8838: contents are written back to the blocks file on disk before it is
 8839: allocated to the new block.
 8840: 
 8841: Although no structure is imposed on the contents of a block, it is
 8842: traditional to display the contents as 16 lines each of 64 characters.  A
 8843: block provides a single, continuous stream of input (for example, it
 8844: acts as a single parse area) -- there are no end-of-line characters
 8845: within a block, and no end-of-file character at the end of a
 8846: block. There are two consequences of this:
 8847: 
 8848: @itemize @bullet
 8849: @item
 8850: The last character of one line wraps straight into the first character
 8851: of the following line
 8852: @item
 8853: The word @code{\} -- comment to end of line -- requires special
 8854: treatment; in the context of a block it causes all characters until the
 8855: end of the current 64-character ``line'' to be ignored.
 8856: @end itemize
 8857: 
 8858: In Gforth, when you use @code{block} with a non-existent block number,
 8859: the current blocks file will be extended to the appropriate size and the
 8860: block buffer will be initialised with spaces.
 8861: 
 8862: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8863: for details) but doesn't encourage the use of blocks; the mechanism is
 8864: only provided for backward compatibility -- ANS Forth requires blocks to
 8865: be available when files are.
 8866: 
 8867: Common techniques that are used when working with blocks include:
 8868: 
 8869: @itemize @bullet
 8870: @item
 8871: A screen editor that allows you to edit blocks without leaving the Forth
 8872: environment.
 8873: @item
 8874: Shadow screens; where every code block has an associated block
 8875: containing comments (for example: code in odd block numbers, comments in
 8876: even block numbers). Typically, the block editor provides a convenient
 8877: mechanism to toggle between code and comments.
 8878: @item
 8879: Load blocks; a single block (typically block 1) contains a number of
 8880: @code{thru} commands which @code{load} the whole of the application.
 8881: @end itemize
 8882: 
 8883: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8884: integrated into a Forth programming environment.
 8885: 
 8886: @comment TODO what about errors on open-blocks?
 8887: 
 8888: doc-open-blocks
 8889: doc-use
 8890: doc-block-offset
 8891: doc-get-block-fid
 8892: doc-block-position
 8893: 
 8894: doc-list
 8895: doc-scr
 8896: 
 8897: doc-block
 8898: doc-buffer
 8899: 
 8900: doc-empty-buffers
 8901: doc-empty-buffer
 8902: doc-update
 8903: doc-updated?
 8904: doc-save-buffers
 8905: doc-save-buffer
 8906: doc-flush
 8907: 
 8908: doc-load
 8909: doc-thru
 8910: doc-+load
 8911: doc-+thru
 8912: doc---gforthman--->
 8913: doc-block-included
 8914: 
 8915: 
 8916: @c -------------------------------------------------------------
 8917: @node Other I/O, OS command line arguments, Blocks, Words
 8918: @section Other I/O
 8919: @cindex I/O - keyboard and display
 8920: 
 8921: @menu
 8922: * Simple numeric output::       Predefined formats
 8923: * Formatted numeric output::    Formatted (pictured) output
 8924: * String Formats::              How Forth stores strings in memory
 8925: * Displaying characters and strings::  Other stuff
 8926: * String words::                Gforth's little string library
 8927: * Terminal output::             Cursor positioning etc.
 8928: * Single-key input::            
 8929: * Line input and conversion::   
 8930: * Pipes::                       How to create your own pipes
 8931: * Xchars and Unicode::          Non-ASCII characters
 8932: @end menu
 8933: 
 8934: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8935: @subsection Simple numeric output
 8936: @cindex numeric output - simple/free-format
 8937: 
 8938: The simplest output functions are those that display numbers from the
 8939: data or floating-point stacks. Floating-point output is always displayed
 8940: using base 10. Numbers displayed from the data stack use the value stored
 8941: in @code{base}.
 8942: 
 8943: 
 8944: doc-.
 8945: doc-dec.
 8946: doc-hex.
 8947: doc-u.
 8948: doc-.r
 8949: doc-u.r
 8950: doc-d.
 8951: doc-ud.
 8952: doc-d.r
 8953: doc-ud.r
 8954: doc-f.
 8955: doc-fe.
 8956: doc-fs.
 8957: doc-f.rdp
 8958: 
 8959: Examples of printing the number 1234.5678E23 in the different floating-point output
 8960: formats are shown below:
 8961: 
 8962: @example
 8963: f. 123456779999999000000000000.
 8964: fe. 123.456779999999E24
 8965: fs. 1.23456779999999E26
 8966: @end example
 8967: 
 8968: 
 8969: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8970: @subsection Formatted numeric output
 8971: @cindex formatted numeric output
 8972: @cindex pictured numeric output
 8973: @cindex numeric output - formatted
 8974: 
 8975: Forth traditionally uses a technique called @dfn{pictured numeric
 8976: output} for formatted printing of integers.  In this technique, digits
 8977: are extracted from the number (using the current output radix defined by
 8978: @code{base}), converted to ASCII codes and appended to a string that is
 8979: built in a scratch-pad area of memory (@pxref{core-idef,
 8980: Implementation-defined options, Implementation-defined
 8981: options}). Arbitrary characters can be appended to the string during the
 8982: extraction process. The completed string is specified by an address
 8983: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8984: under program control.
 8985: 
 8986: All of the integer output words described in the previous section
 8987: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8988: numeric output.
 8989: 
 8990: Three important things to remember about pictured numeric output:
 8991: 
 8992: @itemize @bullet
 8993: @item
 8994: It always operates on double-precision numbers; to display a
 8995: single-precision number, convert it first (for ways of doing this
 8996: @pxref{Double precision}).
 8997: @item
 8998: It always treats the double-precision number as though it were
 8999: unsigned. The examples below show ways of printing signed numbers.
 9000: @item
 9001: The string is built up from right to left; least significant digit first.
 9002: @end itemize
 9003: 
 9004: 
 9005: doc-<#
 9006: doc-<<#
 9007: doc-#
 9008: doc-#s
 9009: doc-hold
 9010: doc-sign
 9011: doc-#>
 9012: doc-#>>
 9013: 
 9014: doc-represent
 9015: doc-f>str-rdp
 9016: doc-f>buf-rdp
 9017: 
 9018: 
 9019: @noindent
 9020: Here are some examples of using pictured numeric output:
 9021: 
 9022: @example
 9023: : my-u. ( u -- )
 9024:   \ Simplest use of pns.. behaves like Standard u. 
 9025:   0              \ convert to unsigned double
 9026:   <<#            \ start conversion
 9027:   #s             \ convert all digits
 9028:   #>             \ complete conversion
 9029:   TYPE SPACE     \ display, with trailing space
 9030:   #>> ;          \ release hold area
 9031: 
 9032: : cents-only ( u -- )
 9033:   0              \ convert to unsigned double
 9034:   <<#            \ start conversion
 9035:   # #            \ convert two least-significant digits
 9036:   #>             \ complete conversion, discard other digits
 9037:   TYPE SPACE     \ display, with trailing space
 9038:   #>> ;          \ release hold area
 9039: 
 9040: : dollars-and-cents ( u -- )
 9041:   0              \ convert to unsigned double
 9042:   <<#            \ start conversion
 9043:   # #            \ convert two least-significant digits
 9044:   [char] . hold  \ insert decimal point
 9045:   #s             \ convert remaining digits
 9046:   [char] $ hold  \ append currency symbol
 9047:   #>             \ complete conversion
 9048:   TYPE SPACE     \ display, with trailing space
 9049:   #>> ;          \ release hold area
 9050: 
 9051: : my-. ( n -- )
 9052:   \ handling negatives.. behaves like Standard .
 9053:   s>d            \ convert to signed double
 9054:   swap over dabs \ leave sign byte followed by unsigned double
 9055:   <<#            \ start conversion
 9056:   #s             \ convert all digits
 9057:   rot sign       \ get at sign byte, append "-" if needed
 9058:   #>             \ complete conversion
 9059:   TYPE SPACE     \ display, with trailing space
 9060:   #>> ;          \ release hold area
 9061: 
 9062: : account. ( n -- )
 9063:   \ accountants don't like minus signs, they use parentheses
 9064:   \ for negative numbers
 9065:   s>d            \ convert to signed double
 9066:   swap over dabs \ leave sign byte followed by unsigned double
 9067:   <<#            \ start conversion
 9068:   2 pick         \ get copy of sign byte
 9069:   0< IF [char] ) hold THEN \ right-most character of output
 9070:   #s             \ convert all digits
 9071:   rot            \ get at sign byte
 9072:   0< IF [char] ( hold THEN
 9073:   #>             \ complete conversion
 9074:   TYPE SPACE     \ display, with trailing space
 9075:   #>> ;          \ release hold area
 9076: 
 9077: @end example
 9078: 
 9079: Here are some examples of using these words:
 9080: 
 9081: @example
 9082: 1 my-u. 1
 9083: hex -1 my-u. decimal FFFFFFFF
 9084: 1 cents-only 01
 9085: 1234 cents-only 34
 9086: 2 dollars-and-cents $0.02
 9087: 1234 dollars-and-cents $12.34
 9088: 123 my-. 123
 9089: -123 my. -123
 9090: 123 account. 123
 9091: -456 account. (456)
 9092: @end example
 9093: 
 9094: 
 9095: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 9096: @subsection String Formats
 9097: @cindex strings - see character strings
 9098: @cindex character strings - formats
 9099: @cindex I/O - see character strings
 9100: @cindex counted strings
 9101: 
 9102: @c anton: this does not really belong here; maybe the memory section,
 9103: @c  or the principles chapter
 9104: 
 9105: Forth commonly uses two different methods for representing character
 9106: strings:
 9107: 
 9108: @itemize @bullet
 9109: @item
 9110: @cindex address of counted string
 9111: @cindex counted string
 9112: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 9113: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 9114: string and the string occupies the subsequent @i{n} char addresses in
 9115: memory.
 9116: @item
 9117: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 9118: of the string in characters, and @i{c-addr} is the address of the
 9119: first byte of the string.
 9120: @end itemize
 9121: 
 9122: ANS Forth encourages the use of the second format when representing
 9123: strings.
 9124: 
 9125: 
 9126: doc-count
 9127: 
 9128: 
 9129: For words that move, copy and search for strings see @ref{Memory
 9130: Blocks}. For words that display characters and strings see
 9131: @ref{Displaying characters and strings}.
 9132: 
 9133: @node Displaying characters and strings, String words, String Formats, Other I/O
 9134: @subsection Displaying characters and strings
 9135: @cindex characters - compiling and displaying
 9136: @cindex character strings - compiling and displaying
 9137: 
 9138: This section starts with a glossary of Forth words and ends with a set
 9139: of examples.
 9140: 
 9141: doc-bl
 9142: doc-space
 9143: doc-spaces
 9144: doc-emit
 9145: doc-toupper
 9146: doc-."
 9147: doc-.(
 9148: doc-.\"
 9149: doc-type
 9150: doc-typewhite
 9151: doc-cr
 9152: @cindex cursor control
 9153: doc-s"
 9154: doc-s\"
 9155: doc-c"
 9156: doc-char
 9157: doc-[char]
 9158: 
 9159: 
 9160: @noindent
 9161: As an example, consider the following text, stored in a file @file{test.fs}:
 9162: 
 9163: @example
 9164: .( text-1)
 9165: : my-word
 9166:   ." text-2" cr
 9167:   .( text-3)
 9168: ;
 9169: 
 9170: ." text-4"
 9171: 
 9172: : my-char
 9173:   [char] ALPHABET emit
 9174:   char emit
 9175: ;
 9176: @end example
 9177: 
 9178: When you load this code into Gforth, the following output is generated:
 9179: 
 9180: @example
 9181: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 9182: @end example
 9183: 
 9184: @itemize @bullet
 9185: @item
 9186: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 9187: is an immediate word; it behaves in the same way whether it is used inside
 9188: or outside a colon definition.
 9189: @item
 9190: Message @code{text-4} is displayed because of Gforth's added interpretation
 9191: semantics for @code{."}.
 9192: @item
 9193: Message @code{text-2} is @i{not} displayed, because the text interpreter
 9194: performs the compilation semantics for @code{."} within the definition of
 9195: @code{my-word}.
 9196: @end itemize
 9197: 
 9198: Here are some examples of executing @code{my-word} and @code{my-char}:
 9199: 
 9200: @example
 9201: @kbd{my-word @key{RET}} text-2
 9202:  ok
 9203: @kbd{my-char fred @key{RET}} Af ok
 9204: @kbd{my-char jim @key{RET}} Aj ok
 9205: @end example
 9206: 
 9207: @itemize @bullet
 9208: @item
 9209: Message @code{text-2} is displayed because of the run-time behaviour of
 9210: @code{."}.
 9211: @item
 9212: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 9213: on the stack at run-time. @code{emit} always displays the character
 9214: when @code{my-char} is executed.
 9215: @item
 9216: @code{char} parses a string at run-time and the second @code{emit} displays
 9217: the first character of the string.
 9218: @item
 9219: If you type @code{see my-char} you can see that @code{[char]} discarded
 9220: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 9221: definition of @code{my-char}.
 9222: @end itemize
 9223: 
 9224: @node String words, Terminal output, Displaying characters and strings, Other I/O
 9225: @subsection String words
 9226: @cindex string words
 9227: 
 9228: The following string library stores strings in ordinary variables,
 9229: which then contain a pointer to a counted string stored allocated from
 9230: the heap.  Instead of a count byte, there's a whole count cell,
 9231: sufficient for all normal use.  The string library originates from
 9232: bigFORTH.
 9233: 
 9234: doc-delete
 9235: doc-insert
 9236: doc-$!
 9237: doc-$@
 9238: doc-$@len
 9239: doc-$!len
 9240: doc-$del
 9241: doc-$ins
 9242: doc-$+!
 9243: doc-$off
 9244: doc-$init
 9245: doc-$split
 9246: doc-$iter
 9247: 
 9248: @node Terminal output, Single-key input, String words, Other I/O
 9249: @subsection Terminal output
 9250: @cindex output to terminal
 9251: @cindex terminal output
 9252: 
 9253: If you are outputting to a terminal, you may want to control the
 9254: positioning of the cursor:
 9255: @cindex cursor positioning
 9256: 
 9257: doc-at-xy
 9258: 
 9259: In order to know where to position the cursor, it is often helpful to
 9260: know the size of the screen:
 9261: @cindex terminal size 
 9262: 
 9263: doc-form
 9264: 
 9265: And sometimes you want to use:
 9266: @cindex clear screen
 9267: 
 9268: doc-page
 9269: 
 9270: Note that on non-terminals you should use @code{12 emit}, not
 9271: @code{page}, to get a form feed.
 9272: 
 9273: 
 9274: @node Single-key input, Line input and conversion, Terminal output, Other I/O
 9275: @subsection Single-key input
 9276: @cindex single-key input
 9277: @cindex input, single-key
 9278: 
 9279: If you want to get a single printable character, you can use
 9280: @code{key}; to check whether a character is available for @code{key},
 9281: you can use @code{key?}.
 9282: 
 9283: doc-key
 9284: doc-key?
 9285: 
 9286: If you want to process a mix of printable and non-printable
 9287: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
 9288: produces a keyboard event that you have to convert into a character
 9289: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
 9290: 
 9291: Typical code for using EKEY looks like this:
 9292: 
 9293: @example
 9294: ekey ekey>char if ( c )
 9295:   ... \ do something with the character
 9296: else ekey>fkey if ( key-id )
 9297:   case
 9298:     k-up                                  of ... endof
 9299:     k-f1                                  of ... endof
 9300:     k-left k-shift-mask or k-ctrl-mask or of ... endof
 9301:     ...
 9302:   endcase
 9303: else ( keyboard-event )
 9304:   drop \ just ignore an unknown keyboard event type
 9305: then then
 9306: @end example
 9307: 
 9308: doc-ekey
 9309: doc-ekey>char
 9310: doc-ekey>fkey
 9311: doc-ekey?
 9312: 
 9313: The key identifiers for cursor keys are:
 9314: 
 9315: doc-k-left
 9316: doc-k-right
 9317: doc-k-up
 9318: doc-k-down
 9319: doc-k-home
 9320: doc-k-end
 9321: doc-k-prior
 9322: doc-k-next
 9323: doc-k-insert
 9324: doc-k-delete
 9325: 
 9326: The key identifiers for function keys (aka keypad keys) are:
 9327: 
 9328: doc-k-f1
 9329: doc-k-f2
 9330: doc-k-f3
 9331: doc-k-f4
 9332: doc-k-f5
 9333: doc-k-f6
 9334: doc-k-f7
 9335: doc-k-f8
 9336: doc-k-f9
 9337: doc-k-f10
 9338: doc-k-f11
 9339: doc-k-f12
 9340: 
 9341: Note that @code{k-f11} and @code{k-f12} are not as widely available.
 9342: 
 9343: You can combine these key identifiers with masks for various shift keys:
 9344: 
 9345: doc-k-shift-mask
 9346: doc-k-ctrl-mask
 9347: doc-k-alt-mask
 9348: 
 9349: Note that, even if a Forth system has @code{ekey>fkey} and the key
 9350: identifier words, the keys are not necessarily available or it may not
 9351: necessarily be able to report all the keys and all the possible
 9352: combinations with shift masks.  Therefore, write your programs in such
 9353: a way that they are still useful even if the keys and key combinations
 9354: cannot be pressed or are not recognized.
 9355: 
 9356: Examples: Older keyboards often do not have an F11 and F12 key.  If
 9357: you run Gforth in an xterm, the xterm catches a number of combinations
 9358: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
 9359: Gforth currently does not recognize and report combinations with
 9360: multiple shift keys (so the @key{shift-ctrl-left} case in the example
 9361: above would never be entered).
 9362: 
 9363: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
 9364: you need the ANSI.SYS driver to get that behaviour); it works by
 9365: recognizing the escape sequences that ANSI terminals send when such a
 9366: key is pressed.  If you have a terminal that sends other escape
 9367: sequences, you will not get useful results on Gforth.  Other Forth
 9368: systems may work in a different way.
 9369: 
 9370: Gforth also provides a few words for outputting names of function
 9371: keys:
 9372: 
 9373: doc-fkey.
 9374: doc-simple-fkey-string
 9375: 
 9376: 
 9377: @node  Line input and conversion, Pipes, Single-key input, Other I/O
 9378: @subsection Line input and conversion
 9379: @cindex line input from terminal
 9380: @cindex input, linewise from terminal
 9381: @cindex convertin strings to numbers
 9382: @cindex I/O - see input
 9383: 
 9384: For ways of storing character strings in memory see @ref{String Formats}.
 9385: 
 9386: @comment TODO examples for >number >float accept key key? pad parse word refill
 9387: @comment then index them
 9388: 
 9389: Words for inputting one line from the keyboard:
 9390: 
 9391: doc-accept
 9392: doc-edit-line
 9393: 
 9394: Conversion words:
 9395: 
 9396: doc-s>number?
 9397: doc-s>unumber?
 9398: doc->number
 9399: doc->float
 9400: 
 9401: 
 9402: @comment obsolescent words..
 9403: Obsolescent input and conversion words:
 9404: 
 9405: doc-convert
 9406: doc-expect
 9407: doc-span
 9408: 
 9409: 
 9410: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
 9411: @subsection Pipes
 9412: @cindex pipes, creating your own
 9413: 
 9414: In addition to using Gforth in pipes created by other processes
 9415: (@pxref{Gforth in pipes}), you can create your own pipe with
 9416: @code{open-pipe}, and read from or write to it.
 9417: 
 9418: doc-open-pipe
 9419: doc-close-pipe
 9420: 
 9421: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 9422: you don't catch this exception, Gforth will catch it and exit, usually
 9423: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 9424: this, you should wrap a @code{catch} or @code{try} block around the code
 9425: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 9426: problem yourself, and then return to regular processing.
 9427: 
 9428: doc-broken-pipe-error
 9429: 
 9430: @node Xchars and Unicode,  , Pipes, Other I/O
 9431: @subsection Xchars and Unicode
 9432: 
 9433: ASCII is only appropriate for the English language. Most western
 9434: languages however fit somewhat into the Forth frame, since a byte is
 9435: sufficient to encode the few special characters in each (though not
 9436: always the same encoding can be used; latin-1 is most widely used,
 9437: though). For other languages, different char-sets have to be used,
 9438: several of them variable-width. Most prominent representant is
 9439: UTF-8. Let's call these extended characters xchars. The primitive
 9440: fixed-size characters stored as bytes are called pchars in this
 9441: section.
 9442: 
 9443: The xchar words add a few data types:
 9444: 
 9445: @itemize
 9446: 
 9447: @item
 9448: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
 9449: and is a subset of unsigned cell. Note: UTF-8 can not store more that
 9450: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
 9451: character set can be used.
 9452: 
 9453: @item
 9454: @var{xc-addr} is the address of an xchar in memory. Alignment
 9455: requirements are the same as @var{c-addr}. The memory representation of an
 9456: xchar differs from the stack representation, and depends on the
 9457: encoding used. An xchar may use a variable number of pchars in memory.
 9458: 
 9459: @item
 9460: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
 9461: @var{xc-addr}, @var{u} pchars long.
 9462: 
 9463: @end itemize
 9464: 
 9465: doc-xc-size
 9466: doc-x-size
 9467: doc-xc@+
 9468: doc-xc!+?
 9469: doc-xchar+
 9470: doc-xchar-
 9471: doc-+x/string
 9472: doc-x\string-
 9473: doc--trailing-garbage
 9474: doc-x-width
 9475: doc-xkey
 9476: doc-xemit
 9477: 
 9478: There's a new environment query
 9479: 
 9480: doc-xchar-encoding
 9481: 
 9482: @node OS command line arguments, Locals, Other I/O, Words
 9483: @section OS command line arguments
 9484: @cindex OS command line arguments
 9485: @cindex command line arguments, OS
 9486: @cindex arguments, OS command line
 9487: 
 9488: The usual way to pass arguments to Gforth programs on the command line
 9489: is via the @option{-e} option, e.g.
 9490: 
 9491: @example
 9492: gforth -e "123 456" foo.fs -e bye
 9493: @end example
 9494: 
 9495: However, you may want to interpret the command-line arguments directly.
 9496: In that case, you can access the (image-specific) command-line arguments
 9497: through @code{next-arg}:
 9498: 
 9499: doc-next-arg
 9500: 
 9501: Here's an example program @file{echo.fs} for @code{next-arg}:
 9502: 
 9503: @example
 9504: : echo ( -- )
 9505:     begin
 9506: 	next-arg 2dup 0 0 d<> while
 9507: 	    type space
 9508:     repeat
 9509:     2drop ;
 9510: 
 9511: echo cr bye
 9512: @end example
 9513: 
 9514: This can be invoked with
 9515: 
 9516: @example
 9517: gforth echo.fs hello world
 9518: @end example
 9519: 
 9520: and it will print
 9521: 
 9522: @example
 9523: hello world
 9524: @end example
 9525: 
 9526: The next lower level of dealing with the OS command line are the
 9527: following words:
 9528: 
 9529: doc-arg
 9530: doc-shift-args
 9531: 
 9532: Finally, at the lowest level Gforth provides the following words:
 9533: 
 9534: doc-argc
 9535: doc-argv
 9536: 
 9537: @c -------------------------------------------------------------
 9538: @node Locals, Structures, OS command line arguments, Words
 9539: @section Locals
 9540: @cindex locals
 9541: 
 9542: Local variables can make Forth programming more enjoyable and Forth
 9543: programs easier to read. Unfortunately, the locals of ANS Forth are
 9544: laden with restrictions. Therefore, we provide not only the ANS Forth
 9545: locals wordset, but also our own, more powerful locals wordset (we
 9546: implemented the ANS Forth locals wordset through our locals wordset).
 9547: 
 9548: The ideas in this section have also been published in M. Anton Ertl,
 9549: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9550: Automatic Scoping of Local Variables}}, EuroForth '94.
 9551: 
 9552: @menu
 9553: * Gforth locals::               
 9554: * ANS Forth locals::            
 9555: @end menu
 9556: 
 9557: @node Gforth locals, ANS Forth locals, Locals, Locals
 9558: @subsection Gforth locals
 9559: @cindex Gforth locals
 9560: @cindex locals, Gforth style
 9561: 
 9562: Locals can be defined with
 9563: 
 9564: @example
 9565: @{ local1 local2 ... -- comment @}
 9566: @end example
 9567: or
 9568: @example
 9569: @{ local1 local2 ... @}
 9570: @end example
 9571: 
 9572: E.g.,
 9573: @example
 9574: : max @{ n1 n2 -- n3 @}
 9575:  n1 n2 > if
 9576:    n1
 9577:  else
 9578:    n2
 9579:  endif ;
 9580: @end example
 9581: 
 9582: The similarity of locals definitions with stack comments is intended. A
 9583: locals definition often replaces the stack comment of a word. The order
 9584: of the locals corresponds to the order in a stack comment and everything
 9585: after the @code{--} is really a comment.
 9586: 
 9587: This similarity has one disadvantage: It is too easy to confuse locals
 9588: declarations with stack comments, causing bugs and making them hard to
 9589: find. However, this problem can be avoided by appropriate coding
 9590: conventions: Do not use both notations in the same program. If you do,
 9591: they should be distinguished using additional means, e.g. by position.
 9592: 
 9593: @cindex types of locals
 9594: @cindex locals types
 9595: The name of the local may be preceded by a type specifier, e.g.,
 9596: @code{F:} for a floating point value:
 9597: 
 9598: @example
 9599: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9600: \ complex multiplication
 9601:  Ar Br f* Ai Bi f* f-
 9602:  Ar Bi f* Ai Br f* f+ ;
 9603: @end example
 9604: 
 9605: @cindex flavours of locals
 9606: @cindex locals flavours
 9607: @cindex value-flavoured locals
 9608: @cindex variable-flavoured locals
 9609: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9610: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9611: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9612: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9613: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9614: produces its address (which becomes invalid when the variable's scope is
 9615: left). E.g., the standard word @code{emit} can be defined in terms of
 9616: @code{type} like this:
 9617: 
 9618: @example
 9619: : emit @{ C^ char* -- @}
 9620:     char* 1 type ;
 9621: @end example
 9622: 
 9623: @cindex default type of locals
 9624: @cindex locals, default type
 9625: A local without type specifier is a @code{W:} local. Both flavours of
 9626: locals are initialized with values from the data or FP stack.
 9627: 
 9628: Currently there is no way to define locals with user-defined data
 9629: structures, but we are working on it.
 9630: 
 9631: Gforth allows defining locals everywhere in a colon definition. This
 9632: poses the following questions:
 9633: 
 9634: @menu
 9635: * Where are locals visible by name?::  
 9636: * How long do locals live?::    
 9637: * Locals programming style::    
 9638: * Locals implementation::       
 9639: @end menu
 9640: 
 9641: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9642: @subsubsection Where are locals visible by name?
 9643: @cindex locals visibility
 9644: @cindex visibility of locals
 9645: @cindex scope of locals
 9646: 
 9647: Basically, the answer is that locals are visible where you would expect
 9648: it in block-structured languages, and sometimes a little longer. If you
 9649: want to restrict the scope of a local, enclose its definition in
 9650: @code{SCOPE}...@code{ENDSCOPE}.
 9651: 
 9652: 
 9653: doc-scope
 9654: doc-endscope
 9655: 
 9656: 
 9657: These words behave like control structure words, so you can use them
 9658: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9659: arbitrary ways.
 9660: 
 9661: If you want a more exact answer to the visibility question, here's the
 9662: basic principle: A local is visible in all places that can only be
 9663: reached through the definition of the local@footnote{In compiler
 9664: construction terminology, all places dominated by the definition of the
 9665: local.}. In other words, it is not visible in places that can be reached
 9666: without going through the definition of the local. E.g., locals defined
 9667: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9668: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9669: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9670: 
 9671: The reasoning behind this solution is: We want to have the locals
 9672: visible as long as it is meaningful. The user can always make the
 9673: visibility shorter by using explicit scoping. In a place that can
 9674: only be reached through the definition of a local, the meaning of a
 9675: local name is clear. In other places it is not: How is the local
 9676: initialized at the control flow path that does not contain the
 9677: definition? Which local is meant, if the same name is defined twice in
 9678: two independent control flow paths?
 9679: 
 9680: This should be enough detail for nearly all users, so you can skip the
 9681: rest of this section. If you really must know all the gory details and
 9682: options, read on.
 9683: 
 9684: In order to implement this rule, the compiler has to know which places
 9685: are unreachable. It knows this automatically after @code{AHEAD},
 9686: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9687: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9688: compiler that the control flow never reaches that place. If
 9689: @code{UNREACHABLE} is not used where it could, the only consequence is
 9690: that the visibility of some locals is more limited than the rule above
 9691: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9692: lie to the compiler), buggy code will be produced.
 9693: 
 9694: 
 9695: doc-unreachable
 9696: 
 9697: 
 9698: Another problem with this rule is that at @code{BEGIN}, the compiler
 9699: does not know which locals will be visible on the incoming
 9700: back-edge. All problems discussed in the following are due to this
 9701: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9702: loops as examples; the discussion also applies to @code{?DO} and other
 9703: loops). Perhaps the most insidious example is:
 9704: @example
 9705: AHEAD
 9706: BEGIN
 9707:   x
 9708: [ 1 CS-ROLL ] THEN
 9709:   @{ x @}
 9710:   ...
 9711: UNTIL
 9712: @end example
 9713: 
 9714: This should be legal according to the visibility rule. The use of
 9715: @code{x} can only be reached through the definition; but that appears
 9716: textually below the use.
 9717: 
 9718: From this example it is clear that the visibility rules cannot be fully
 9719: implemented without major headaches. Our implementation treats common
 9720: cases as advertised and the exceptions are treated in a safe way: The
 9721: compiler makes a reasonable guess about the locals visible after a
 9722: @code{BEGIN}; if it is too pessimistic, the
 9723: user will get a spurious error about the local not being defined; if the
 9724: compiler is too optimistic, it will notice this later and issue a
 9725: warning. In the case above the compiler would complain about @code{x}
 9726: being undefined at its use. You can see from the obscure examples in
 9727: this section that it takes quite unusual control structures to get the
 9728: compiler into trouble, and even then it will often do fine.
 9729: 
 9730: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9731: is that all locals visible before the @code{BEGIN} will also be
 9732: visible after the @code{BEGIN}. This guess is valid for all loops that
 9733: are entered only through the @code{BEGIN}, in particular, for normal
 9734: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9735: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9736: compiler. When the branch to the @code{BEGIN} is finally generated by
 9737: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9738: warns the user if it was too optimistic:
 9739: @example
 9740: IF
 9741:   @{ x @}
 9742: BEGIN
 9743:   \ x ? 
 9744: [ 1 cs-roll ] THEN
 9745:   ...
 9746: UNTIL
 9747: @end example
 9748: 
 9749: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9750: optimistically assumes that it lives until the @code{THEN}. It notices
 9751: this difference when it compiles the @code{UNTIL} and issues a
 9752: warning. The user can avoid the warning, and make sure that @code{x}
 9753: is not used in the wrong area by using explicit scoping:
 9754: @example
 9755: IF
 9756:   SCOPE
 9757:   @{ x @}
 9758:   ENDSCOPE
 9759: BEGIN
 9760: [ 1 cs-roll ] THEN
 9761:   ...
 9762: UNTIL
 9763: @end example
 9764: 
 9765: Since the guess is optimistic, there will be no spurious error messages
 9766: about undefined locals.
 9767: 
 9768: If the @code{BEGIN} is not reachable from above (e.g., after
 9769: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9770: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9771: defined later. Therefore, the compiler assumes that no locals are
 9772: visible after the @code{BEGIN}. However, the user can use
 9773: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9774: visible at the BEGIN as at the point where the top control-flow stack
 9775: item was created.
 9776: 
 9777: 
 9778: doc-assume-live
 9779: 
 9780: 
 9781: @noindent
 9782: E.g.,
 9783: @example
 9784: @{ x @}
 9785: AHEAD
 9786: ASSUME-LIVE
 9787: BEGIN
 9788:   x
 9789: [ 1 CS-ROLL ] THEN
 9790:   ...
 9791: UNTIL
 9792: @end example
 9793: 
 9794: Other cases where the locals are defined before the @code{BEGIN} can be
 9795: handled by inserting an appropriate @code{CS-ROLL} before the
 9796: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9797: behind the @code{ASSUME-LIVE}).
 9798: 
 9799: Cases where locals are defined after the @code{BEGIN} (but should be
 9800: visible immediately after the @code{BEGIN}) can only be handled by
 9801: rearranging the loop. E.g., the ``most insidious'' example above can be
 9802: arranged into:
 9803: @example
 9804: BEGIN
 9805:   @{ x @}
 9806:   ... 0=
 9807: WHILE
 9808:   x
 9809: REPEAT
 9810: @end example
 9811: 
 9812: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9813: @subsubsection How long do locals live?
 9814: @cindex locals lifetime
 9815: @cindex lifetime of locals
 9816: 
 9817: The right answer for the lifetime question would be: A local lives at
 9818: least as long as it can be accessed. For a value-flavoured local this
 9819: means: until the end of its visibility. However, a variable-flavoured
 9820: local could be accessed through its address far beyond its visibility
 9821: scope. Ultimately, this would mean that such locals would have to be
 9822: garbage collected. Since this entails un-Forth-like implementation
 9823: complexities, I adopted the same cowardly solution as some other
 9824: languages (e.g., C): The local lives only as long as it is visible;
 9825: afterwards its address is invalid (and programs that access it
 9826: afterwards are erroneous).
 9827: 
 9828: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9829: @subsubsection Locals programming style
 9830: @cindex locals programming style
 9831: @cindex programming style, locals
 9832: 
 9833: The freedom to define locals anywhere has the potential to change
 9834: programming styles dramatically. In particular, the need to use the
 9835: return stack for intermediate storage vanishes. Moreover, all stack
 9836: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9837: determined arguments) can be eliminated: If the stack items are in the
 9838: wrong order, just write a locals definition for all of them; then
 9839: write the items in the order you want.
 9840: 
 9841: This seems a little far-fetched and eliminating stack manipulations is
 9842: unlikely to become a conscious programming objective. Still, the number
 9843: of stack manipulations will be reduced dramatically if local variables
 9844: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9845: a traditional implementation of @code{max}).
 9846: 
 9847: This shows one potential benefit of locals: making Forth programs more
 9848: readable. Of course, this benefit will only be realized if the
 9849: programmers continue to honour the principle of factoring instead of
 9850: using the added latitude to make the words longer.
 9851: 
 9852: @cindex single-assignment style for locals
 9853: Using @code{TO} can and should be avoided.  Without @code{TO},
 9854: every value-flavoured local has only a single assignment and many
 9855: advantages of functional languages apply to Forth. I.e., programs are
 9856: easier to analyse, to optimize and to read: It is clear from the
 9857: definition what the local stands for, it does not turn into something
 9858: different later.
 9859: 
 9860: E.g., a definition using @code{TO} might look like this:
 9861: @example
 9862: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9863:  u1 u2 min 0
 9864:  ?do
 9865:    addr1 c@@ addr2 c@@ -
 9866:    ?dup-if
 9867:      unloop exit
 9868:    then
 9869:    addr1 char+ TO addr1
 9870:    addr2 char+ TO addr2
 9871:  loop
 9872:  u1 u2 - ;
 9873: @end example
 9874: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9875: every loop iteration. @code{strcmp} is a typical example of the
 9876: readability problems of using @code{TO}. When you start reading
 9877: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9878: string. Only near the end of the loop you realize that it is something
 9879: else.
 9880: 
 9881: This can be avoided by defining two locals at the start of the loop that
 9882: are initialized with the right value for the current iteration.
 9883: @example
 9884: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9885:  addr1 addr2
 9886:  u1 u2 min 0 
 9887:  ?do @{ s1 s2 @}
 9888:    s1 c@@ s2 c@@ -
 9889:    ?dup-if
 9890:      unloop exit
 9891:    then
 9892:    s1 char+ s2 char+
 9893:  loop
 9894:  2drop
 9895:  u1 u2 - ;
 9896: @end example
 9897: Here it is clear from the start that @code{s1} has a different value
 9898: in every loop iteration.
 9899: 
 9900: @node Locals implementation,  , Locals programming style, Gforth locals
 9901: @subsubsection Locals implementation
 9902: @cindex locals implementation
 9903: @cindex implementation of locals
 9904: 
 9905: @cindex locals stack
 9906: Gforth uses an extra locals stack. The most compelling reason for
 9907: this is that the return stack is not float-aligned; using an extra stack
 9908: also eliminates the problems and restrictions of using the return stack
 9909: as locals stack. Like the other stacks, the locals stack grows toward
 9910: lower addresses. A few primitives allow an efficient implementation:
 9911: 
 9912: 
 9913: doc-@local#
 9914: doc-f@local#
 9915: doc-laddr#
 9916: doc-lp+!#
 9917: doc-lp!
 9918: doc->l
 9919: doc-f>l
 9920: 
 9921: 
 9922: In addition to these primitives, some specializations of these
 9923: primitives for commonly occurring inline arguments are provided for
 9924: efficiency reasons, e.g., @code{@@local0} as specialization of
 9925: @code{@@local#} for the inline argument 0. The following compiling words
 9926: compile the right specialized version, or the general version, as
 9927: appropriate:
 9928: 
 9929: 
 9930: @c doc-compile-@local
 9931: @c doc-compile-f@local
 9932: doc-compile-lp+!
 9933: 
 9934: 
 9935: Combinations of conditional branches and @code{lp+!#} like
 9936: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9937: is taken) are provided for efficiency and correctness in loops.
 9938: 
 9939: A special area in the dictionary space is reserved for keeping the
 9940: local variable names. @code{@{} switches the dictionary pointer to this
 9941: area and @code{@}} switches it back and generates the locals
 9942: initializing code. @code{W:} etc.@ are normal defining words. This
 9943: special area is cleared at the start of every colon definition.
 9944: 
 9945: @cindex word list for defining locals
 9946: A special feature of Gforth's dictionary is used to implement the
 9947: definition of locals without type specifiers: every word list (aka
 9948: vocabulary) has its own methods for searching
 9949: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9950: with a special search method: When it is searched for a word, it
 9951: actually creates that word using @code{W:}. @code{@{} changes the search
 9952: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9953: and then the word list for defining locals without type specifiers.
 9954: 
 9955: The lifetime rules support a stack discipline within a colon
 9956: definition: The lifetime of a local is either nested with other locals
 9957: lifetimes or it does not overlap them.
 9958: 
 9959: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9960: pointer manipulation is generated. Between control structure words
 9961: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9962: is the simplest of the other three control flow words. It has to
 9963: restore the locals stack depth of the corresponding @code{BEGIN}
 9964: before branching. The code looks like this:
 9965: @format
 9966: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9967: @code{branch} <begin>
 9968: @end format
 9969: 
 9970: @code{UNTIL} is a little more complicated: If it branches back, it
 9971: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9972: the locals stack must not be changed. The compiler generates the
 9973: following code:
 9974: @format
 9975: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9976: @end format
 9977: The locals stack pointer is only adjusted if the branch is taken.
 9978: 
 9979: @code{THEN} can produce somewhat inefficient code:
 9980: @format
 9981: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9982: <orig target>:
 9983: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9984: @end format
 9985: The second @code{lp+!#} adjusts the locals stack pointer from the
 9986: level at the @i{orig} point to the level after the @code{THEN}. The
 9987: first @code{lp+!#} adjusts the locals stack pointer from the current
 9988: level to the level at the orig point, so the complete effect is an
 9989: adjustment from the current level to the right level after the
 9990: @code{THEN}.
 9991: 
 9992: @cindex locals information on the control-flow stack
 9993: @cindex control-flow stack items, locals information
 9994: In a conventional Forth implementation a dest control-flow stack entry
 9995: is just the target address and an orig entry is just the address to be
 9996: patched. Our locals implementation adds a word list to every orig or dest
 9997: item. It is the list of locals visible (or assumed visible) at the point
 9998: described by the entry. Our implementation also adds a tag to identify
 9999: the kind of entry, in particular to differentiate between live and dead
10000: (reachable and unreachable) orig entries.
10001: 
10002: A few unusual operations have to be performed on locals word lists:
10003: 
10004: 
10005: doc-common-list
10006: doc-sub-list?
10007: doc-list-size
10008: 
10009: 
10010: Several features of our locals word list implementation make these
10011: operations easy to implement: The locals word lists are organised as
10012: linked lists; the tails of these lists are shared, if the lists
10013: contain some of the same locals; and the address of a name is greater
10014: than the address of the names behind it in the list.
10015: 
10016: Another important implementation detail is the variable
10017: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
10018: determine if they can be reached directly or only through the branch
10019: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
10020: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
10021: definition, by @code{BEGIN} and usually by @code{THEN}.
10022: 
10023: Counted loops are similar to other loops in most respects, but
10024: @code{LEAVE} requires special attention: It performs basically the same
10025: service as @code{AHEAD}, but it does not create a control-flow stack
10026: entry. Therefore the information has to be stored elsewhere;
10027: traditionally, the information was stored in the target fields of the
10028: branches created by the @code{LEAVE}s, by organizing these fields into a
10029: linked list. Unfortunately, this clever trick does not provide enough
10030: space for storing our extended control flow information. Therefore, we
10031: introduce another stack, the leave stack. It contains the control-flow
10032: stack entries for all unresolved @code{LEAVE}s.
10033: 
10034: Local names are kept until the end of the colon definition, even if
10035: they are no longer visible in any control-flow path. In a few cases
10036: this may lead to increased space needs for the locals name area, but
10037: usually less than reclaiming this space would cost in code size.
10038: 
10039: 
10040: @node ANS Forth locals,  , Gforth locals, Locals
10041: @subsection ANS Forth locals
10042: @cindex locals, ANS Forth style
10043: 
10044: The ANS Forth locals wordset does not define a syntax for locals, but
10045: words that make it possible to define various syntaxes. One of the
10046: possible syntaxes is a subset of the syntax we used in the Gforth locals
10047: wordset, i.e.:
10048: 
10049: @example
10050: @{ local1 local2 ... -- comment @}
10051: @end example
10052: @noindent
10053: or
10054: @example
10055: @{ local1 local2 ... @}
10056: @end example
10057: 
10058: The order of the locals corresponds to the order in a stack comment. The
10059: restrictions are:
10060: 
10061: @itemize @bullet
10062: @item
10063: Locals can only be cell-sized values (no type specifiers are allowed).
10064: @item
10065: Locals can be defined only outside control structures.
10066: @item
10067: Locals can interfere with explicit usage of the return stack. For the
10068: exact (and long) rules, see the standard. If you don't use return stack
10069: accessing words in a definition using locals, you will be all right. The
10070: purpose of this rule is to make locals implementation on the return
10071: stack easier.
10072: @item
10073: The whole definition must be in one line.
10074: @end itemize
10075: 
10076: Locals defined in ANS Forth behave like @code{VALUE}s
10077: (@pxref{Values}). I.e., they are initialized from the stack. Using their
10078: name produces their value. Their value can be changed using @code{TO}.
10079: 
10080: Since the syntax above is supported by Gforth directly, you need not do
10081: anything to use it. If you want to port a program using this syntax to
10082: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
10083: syntax on the other system.
10084: 
10085: Note that a syntax shown in the standard, section A.13 looks
10086: similar, but is quite different in having the order of locals
10087: reversed. Beware!
10088: 
10089: The ANS Forth locals wordset itself consists of one word:
10090: 
10091: doc-(local)
10092: 
10093: The ANS Forth locals extension wordset defines a syntax using
10094: @code{locals|}, but it is so awful that we strongly recommend not to use
10095: it. We have implemented this syntax to make porting to Gforth easy, but
10096: do not document it here. The problem with this syntax is that the locals
10097: are defined in an order reversed with respect to the standard stack
10098: comment notation, making programs harder to read, and easier to misread
10099: and miswrite. The only merit of this syntax is that it is easy to
10100: implement using the ANS Forth locals wordset.
10101: 
10102: 
10103: @c ----------------------------------------------------------
10104: @node Structures, Object-oriented Forth, Locals, Words
10105: @section  Structures
10106: @cindex structures
10107: @cindex records
10108: 
10109: This section presents the structure package that comes with Gforth. A
10110: version of the package implemented in ANS Forth is available in
10111: @file{compat/struct.fs}. This package was inspired by a posting on
10112: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
10113: possibly John Hayes). A version of this section has been published in
10114: M. Anton Ertl,
10115: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
10116: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10117: 13--16. Marcel Hendrix provided helpful comments.
10118: 
10119: @menu
10120: * Why explicit structure support?::  
10121: * Structure Usage::             
10122: * Structure Naming Convention::  
10123: * Structure Implementation::    
10124: * Structure Glossary::          
10125: * Forth200x Structures::        
10126: @end menu
10127: 
10128: @node Why explicit structure support?, Structure Usage, Structures, Structures
10129: @subsection Why explicit structure support?
10130: 
10131: @cindex address arithmetic for structures
10132: @cindex structures using address arithmetic
10133: If we want to use a structure containing several fields, we could simply
10134: reserve memory for it, and access the fields using address arithmetic
10135: (@pxref{Address arithmetic}). As an example, consider a structure with
10136: the following fields
10137: 
10138: @table @code
10139: @item a
10140: is a float
10141: @item b
10142: is a cell
10143: @item c
10144: is a float
10145: @end table
10146: 
10147: Given the (float-aligned) base address of the structure we get the
10148: address of the field
10149: 
10150: @table @code
10151: @item a
10152: without doing anything further.
10153: @item b
10154: with @code{float+}
10155: @item c
10156: with @code{float+ cell+ faligned}
10157: @end table
10158: 
10159: It is easy to see that this can become quite tiring. 
10160: 
10161: Moreover, it is not very readable, because seeing a
10162: @code{cell+} tells us neither which kind of structure is
10163: accessed nor what field is accessed; we have to somehow infer the kind
10164: of structure, and then look up in the documentation, which field of
10165: that structure corresponds to that offset.
10166: 
10167: Finally, this kind of address arithmetic also causes maintenance
10168: troubles: If you add or delete a field somewhere in the middle of the
10169: structure, you have to find and change all computations for the fields
10170: afterwards.
10171: 
10172: So, instead of using @code{cell+} and friends directly, how
10173: about storing the offsets in constants:
10174: 
10175: @example
10176: 0 constant a-offset
10177: 0 float+ constant b-offset
10178: 0 float+ cell+ faligned c-offset
10179: @end example
10180: 
10181: Now we can get the address of field @code{x} with @code{x-offset
10182: +}. This is much better in all respects. Of course, you still
10183: have to change all later offset definitions if you add a field. You can
10184: fix this by declaring the offsets in the following way:
10185: 
10186: @example
10187: 0 constant a-offset
10188: a-offset float+ constant b-offset
10189: b-offset cell+ faligned constant c-offset
10190: @end example
10191: 
10192: Since we always use the offsets with @code{+}, we could use a defining
10193: word @code{cfield} that includes the @code{+} in the action of the
10194: defined word:
10195: 
10196: @example
10197: : cfield ( n "name" -- )
10198:     create ,
10199: does> ( name execution: addr1 -- addr2 )
10200:     @@ + ;
10201: 
10202: 0 cfield a
10203: 0 a float+ cfield b
10204: 0 b cell+ faligned cfield c
10205: @end example
10206: 
10207: Instead of @code{x-offset +}, we now simply write @code{x}.
10208: 
10209: The structure field words now can be used quite nicely. However,
10210: their definition is still a bit cumbersome: We have to repeat the
10211: name, the information about size and alignment is distributed before
10212: and after the field definitions etc.  The structure package presented
10213: here addresses these problems.
10214: 
10215: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10216: @subsection Structure Usage
10217: @cindex structure usage
10218: 
10219: @cindex @code{field} usage
10220: @cindex @code{struct} usage
10221: @cindex @code{end-struct} usage
10222: You can define a structure for a (data-less) linked list with:
10223: @example
10224: struct
10225:     cell% field list-next
10226: end-struct list%
10227: @end example
10228: 
10229: With the address of the list node on the stack, you can compute the
10230: address of the field that contains the address of the next node with
10231: @code{list-next}. E.g., you can determine the length of a list
10232: with:
10233: 
10234: @example
10235: : list-length ( list -- n )
10236: \ "list" is a pointer to the first element of a linked list
10237: \ "n" is the length of the list
10238:     0 BEGIN ( list1 n1 )
10239:         over
10240:     WHILE ( list1 n1 )
10241:         1+ swap list-next @@ swap
10242:     REPEAT
10243:     nip ;
10244: @end example
10245: 
10246: You can reserve memory for a list node in the dictionary with
10247: @code{list% %allot}, which leaves the address of the list node on the
10248: stack. For the equivalent allocation on the heap you can use @code{list%
10249: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10250: use @code{list% %allocate}). You can get the the size of a list
10251: node with @code{list% %size} and its alignment with @code{list%
10252: %alignment}.
10253: 
10254: Note that in ANS Forth the body of a @code{create}d word is
10255: @code{aligned} but not necessarily @code{faligned};
10256: therefore, if you do a:
10257: 
10258: @example
10259: create @emph{name} foo% %allot drop
10260: @end example
10261: 
10262: @noindent
10263: then the memory alloted for @code{foo%} is guaranteed to start at the
10264: body of @code{@emph{name}} only if @code{foo%} contains only character,
10265: cell and double fields.  Therefore, if your structure contains floats,
10266: better use
10267: 
10268: @example
10269: foo% %allot constant @emph{name}
10270: @end example
10271: 
10272: @cindex structures containing structures
10273: You can include a structure @code{foo%} as a field of
10274: another structure, like this:
10275: @example
10276: struct
10277: ...
10278:     foo% field ...
10279: ...
10280: end-struct ...
10281: @end example
10282: 
10283: @cindex structure extension
10284: @cindex extended records
10285: Instead of starting with an empty structure, you can extend an
10286: existing structure. E.g., a plain linked list without data, as defined
10287: above, is hardly useful; You can extend it to a linked list of integers,
10288: like this:@footnote{This feature is also known as @emph{extended
10289: records}. It is the main innovation in the Oberon language; in other
10290: words, adding this feature to Modula-2 led Wirth to create a new
10291: language, write a new compiler etc.  Adding this feature to Forth just
10292: required a few lines of code.}
10293: 
10294: @example
10295: list%
10296:     cell% field intlist-int
10297: end-struct intlist%
10298: @end example
10299: 
10300: @code{intlist%} is a structure with two fields:
10301: @code{list-next} and @code{intlist-int}.
10302: 
10303: @cindex structures containing arrays
10304: You can specify an array type containing @emph{n} elements of
10305: type @code{foo%} like this:
10306: 
10307: @example
10308: foo% @emph{n} *
10309: @end example
10310: 
10311: You can use this array type in any place where you can use a normal
10312: type, e.g., when defining a @code{field}, or with
10313: @code{%allot}.
10314: 
10315: @cindex first field optimization
10316: The first field is at the base address of a structure and the word for
10317: this field (e.g., @code{list-next}) actually does not change the address
10318: on the stack. You may be tempted to leave it away in the interest of
10319: run-time and space efficiency. This is not necessary, because the
10320: structure package optimizes this case: If you compile a first-field
10321: words, no code is generated. So, in the interest of readability and
10322: maintainability you should include the word for the field when accessing
10323: the field.
10324: 
10325: 
10326: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10327: @subsection Structure Naming Convention
10328: @cindex structure naming convention
10329: 
10330: The field names that come to (my) mind are often quite generic, and,
10331: if used, would cause frequent name clashes. E.g., many structures
10332: probably contain a @code{counter} field. The structure names
10333: that come to (my) mind are often also the logical choice for the names
10334: of words that create such a structure.
10335: 
10336: Therefore, I have adopted the following naming conventions: 
10337: 
10338: @itemize @bullet
10339: @cindex field naming convention
10340: @item
10341: The names of fields are of the form
10342: @code{@emph{struct}-@emph{field}}, where
10343: @code{@emph{struct}} is the basic name of the structure, and
10344: @code{@emph{field}} is the basic name of the field. You can
10345: think of field words as converting the (address of the)
10346: structure into the (address of the) field.
10347: 
10348: @cindex structure naming convention
10349: @item
10350: The names of structures are of the form
10351: @code{@emph{struct}%}, where
10352: @code{@emph{struct}} is the basic name of the structure.
10353: @end itemize
10354: 
10355: This naming convention does not work that well for fields of extended
10356: structures; e.g., the integer list structure has a field
10357: @code{intlist-int}, but has @code{list-next}, not
10358: @code{intlist-next}.
10359: 
10360: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10361: @subsection Structure Implementation
10362: @cindex structure implementation
10363: @cindex implementation of structures
10364: 
10365: The central idea in the implementation is to pass the data about the
10366: structure being built on the stack, not in some global
10367: variable. Everything else falls into place naturally once this design
10368: decision is made.
10369: 
10370: The type description on the stack is of the form @emph{align
10371: size}. Keeping the size on the top-of-stack makes dealing with arrays
10372: very simple.
10373: 
10374: @code{field} is a defining word that uses @code{Create}
10375: and @code{DOES>}. The body of the field contains the offset
10376: of the field, and the normal @code{DOES>} action is simply:
10377: 
10378: @example
10379: @@ +
10380: @end example
10381: 
10382: @noindent
10383: i.e., add the offset to the address, giving the stack effect
10384: @i{addr1 -- addr2} for a field.
10385: 
10386: @cindex first field optimization, implementation
10387: This simple structure is slightly complicated by the optimization
10388: for fields with offset 0, which requires a different
10389: @code{DOES>}-part (because we cannot rely on there being
10390: something on the stack if such a field is invoked during
10391: compilation). Therefore, we put the different @code{DOES>}-parts
10392: in separate words, and decide which one to invoke based on the
10393: offset. For a zero offset, the field is basically a noop; it is
10394: immediate, and therefore no code is generated when it is compiled.
10395: 
10396: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
10397: @subsection Structure Glossary
10398: @cindex structure glossary
10399: 
10400: 
10401: doc-%align
10402: doc-%alignment
10403: doc-%alloc
10404: doc-%allocate
10405: doc-%allot
10406: doc-cell%
10407: doc-char%
10408: doc-dfloat%
10409: doc-double%
10410: doc-end-struct
10411: doc-field
10412: doc-float%
10413: doc-naligned
10414: doc-sfloat%
10415: doc-%size
10416: doc-struct
10417: 
10418: 
10419: @node Forth200x Structures,  , Structure Glossary, Structures
10420: @subsection Forth200x Structures
10421: @cindex Structures in Forth200x
10422: 
10423: The Forth 200x standard defines a slightly less convenient form of
10424: structures.  In general (when using @code{field+}, you have to perform
10425: the alignment yourself, but there are a number of convenience words
10426: (e.g., @code{field:} that perform the alignment for you.
10427: 
10428: A typical usage example is:
10429: 
10430: @example
10431: 0
10432:   field:                   s-a
10433:   faligned 2 floats +field s-b
10434: constant s-struct
10435: @end example
10436: 
10437: An alternative way of writing this structure is:
10438: 
10439: @example
10440: begin-structure s-struct
10441:   field:                   s-a
10442:   faligned 2 floats +field s-b
10443: end-structure
10444: @end example
10445: 
10446: doc-begin-structure
10447: doc-end-structure
10448: doc-+field
10449: doc-cfield:
10450: doc-field:
10451: doc-2field:
10452: doc-ffield:
10453: doc-sffield:
10454: doc-dffield:
10455: 
10456: @c -------------------------------------------------------------
10457: @node Object-oriented Forth, Programming Tools, Structures, Words
10458: @section Object-oriented Forth
10459: 
10460: Gforth comes with three packages for object-oriented programming:
10461: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10462: is preloaded, so you have to @code{include} them before use. The most
10463: important differences between these packages (and others) are discussed
10464: in @ref{Comparison with other object models}. All packages are written
10465: in ANS Forth and can be used with any other ANS Forth.
10466: 
10467: @menu
10468: * Why object-oriented programming?::  
10469: * Object-Oriented Terminology::  
10470: * Objects::                     
10471: * OOF::                         
10472: * Mini-OOF::                    
10473: * Comparison with other object models::  
10474: @end menu
10475: 
10476: @c ----------------------------------------------------------------
10477: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10478: @subsection Why object-oriented programming?
10479: @cindex object-oriented programming motivation
10480: @cindex motivation for object-oriented programming
10481: 
10482: Often we have to deal with several data structures (@emph{objects}),
10483: that have to be treated similarly in some respects, but differently in
10484: others. Graphical objects are the textbook example: circles, triangles,
10485: dinosaurs, icons, and others, and we may want to add more during program
10486: development. We want to apply some operations to any graphical object,
10487: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10488: has to do something different for every kind of object.
10489: @comment TODO add some other operations eg perimeter, area
10490: @comment and tie in to concrete examples later..
10491: 
10492: We could implement @code{draw} as a big @code{CASE}
10493: control structure that executes the appropriate code depending on the
10494: kind of object to be drawn. This would be not be very elegant, and,
10495: moreover, we would have to change @code{draw} every time we add
10496: a new kind of graphical object (say, a spaceship).
10497: 
10498: What we would rather do is: When defining spaceships, we would tell
10499: the system: ``Here's how you @code{draw} a spaceship; you figure
10500: out the rest''.
10501: 
10502: This is the problem that all systems solve that (rightfully) call
10503: themselves object-oriented; the object-oriented packages presented here
10504: solve this problem (and not much else).
10505: @comment TODO ?list properties of oo systems.. oo vs o-based?
10506: 
10507: @c ------------------------------------------------------------------------
10508: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10509: @subsection Object-Oriented Terminology
10510: @cindex object-oriented terminology
10511: @cindex terminology for object-oriented programming
10512: 
10513: This section is mainly for reference, so you don't have to understand
10514: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10515: short:
10516: 
10517: @table @emph
10518: @cindex class
10519: @item class
10520: a data structure definition with some extras.
10521: 
10522: @cindex object
10523: @item object
10524: an instance of the data structure described by the class definition.
10525: 
10526: @cindex instance variables
10527: @item instance variables
10528: fields of the data structure.
10529: 
10530: @cindex selector
10531: @cindex method selector
10532: @cindex virtual function
10533: @item selector
10534: (or @emph{method selector}) a word (e.g.,
10535: @code{draw}) that performs an operation on a variety of data
10536: structures (classes). A selector describes @emph{what} operation to
10537: perform. In C++ terminology: a (pure) virtual function.
10538: 
10539: @cindex method
10540: @item method
10541: the concrete definition that performs the operation
10542: described by the selector for a specific class. A method specifies
10543: @emph{how} the operation is performed for a specific class.
10544: 
10545: @cindex selector invocation
10546: @cindex message send
10547: @cindex invoking a selector
10548: @item selector invocation
10549: a call of a selector. One argument of the call (the TOS (top-of-stack))
10550: is used for determining which method is used. In Smalltalk terminology:
10551: a message (consisting of the selector and the other arguments) is sent
10552: to the object.
10553: 
10554: @cindex receiving object
10555: @item receiving object
10556: the object used for determining the method executed by a selector
10557: invocation. In the @file{objects.fs} model, it is the object that is on
10558: the TOS when the selector is invoked. (@emph{Receiving} comes from
10559: the Smalltalk @emph{message} terminology.)
10560: 
10561: @cindex child class
10562: @cindex parent class
10563: @cindex inheritance
10564: @item child class
10565: a class that has (@emph{inherits}) all properties (instance variables,
10566: selectors, methods) from a @emph{parent class}. In Smalltalk
10567: terminology: The subclass inherits from the superclass. In C++
10568: terminology: The derived class inherits from the base class.
10569: 
10570: @end table
10571: 
10572: @c If you wonder about the message sending terminology, it comes from
10573: @c a time when each object had it's own task and objects communicated via
10574: @c message passing; eventually the Smalltalk developers realized that
10575: @c they can do most things through simple (indirect) calls. They kept the
10576: @c terminology.
10577: 
10578: @c --------------------------------------------------------------
10579: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10580: @subsection The @file{objects.fs} model
10581: @cindex objects
10582: @cindex object-oriented programming
10583: 
10584: @cindex @file{objects.fs}
10585: @cindex @file{oof.fs}
10586: 
10587: This section describes the @file{objects.fs} package. This material also
10588: has been published in M. Anton Ertl,
10589: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10590: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10591: 37--43.
10592: @c McKewan's and Zsoter's packages
10593: 
10594: This section assumes that you have read @ref{Structures}.
10595: 
10596: The techniques on which this model is based have been used to implement
10597: the parser generator, Gray, and have also been used in Gforth for
10598: implementing the various flavours of word lists (hashed or not,
10599: case-sensitive or not, special-purpose word lists for locals etc.).
10600: 
10601: 
10602: @menu
10603: * Properties of the Objects model::  
10604: * Basic Objects Usage::         
10605: * The Objects base class::      
10606: * Creating objects::            
10607: * Object-Oriented Programming Style::  
10608: * Class Binding::               
10609: * Method conveniences::         
10610: * Classes and Scoping::         
10611: * Dividing classes::            
10612: * Object Interfaces::           
10613: * Objects Implementation::      
10614: * Objects Glossary::            
10615: @end menu
10616: 
10617: Marcel Hendrix provided helpful comments on this section.
10618: 
10619: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10620: @subsubsection Properties of the @file{objects.fs} model
10621: @cindex @file{objects.fs} properties
10622: 
10623: @itemize @bullet
10624: @item
10625: It is straightforward to pass objects on the stack. Passing
10626: selectors on the stack is a little less convenient, but possible.
10627: 
10628: @item
10629: Objects are just data structures in memory, and are referenced by their
10630: address. You can create words for objects with normal defining words
10631: like @code{constant}. Likewise, there is no difference between instance
10632: variables that contain objects and those that contain other data.
10633: 
10634: @item
10635: Late binding is efficient and easy to use.
10636: 
10637: @item
10638: It avoids parsing, and thus avoids problems with state-smartness
10639: and reduced extensibility; for convenience there are a few parsing
10640: words, but they have non-parsing counterparts. There are also a few
10641: defining words that parse. This is hard to avoid, because all standard
10642: defining words parse (except @code{:noname}); however, such
10643: words are not as bad as many other parsing words, because they are not
10644: state-smart.
10645: 
10646: @item
10647: It does not try to incorporate everything. It does a few things and does
10648: them well (IMO). In particular, this model was not designed to support
10649: information hiding (although it has features that may help); you can use
10650: a separate package for achieving this.
10651: 
10652: @item
10653: It is layered; you don't have to learn and use all features to use this
10654: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10655: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10656: are optional and independent of each other.
10657: 
10658: @item
10659: An implementation in ANS Forth is available.
10660: 
10661: @end itemize
10662: 
10663: 
10664: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10665: @subsubsection Basic @file{objects.fs} Usage
10666: @cindex basic objects usage
10667: @cindex objects, basic usage
10668: 
10669: You can define a class for graphical objects like this:
10670: 
10671: @cindex @code{class} usage
10672: @cindex @code{end-class} usage
10673: @cindex @code{selector} usage
10674: @example
10675: object class \ "object" is the parent class
10676:   selector draw ( x y graphical -- )
10677: end-class graphical
10678: @end example
10679: 
10680: This code defines a class @code{graphical} with an
10681: operation @code{draw}.  We can perform the operation
10682: @code{draw} on any @code{graphical} object, e.g.:
10683: 
10684: @example
10685: 100 100 t-rex draw
10686: @end example
10687: 
10688: @noindent
10689: where @code{t-rex} is a word (say, a constant) that produces a
10690: graphical object.
10691: 
10692: @comment TODO add a 2nd operation eg perimeter.. and use for
10693: @comment a concrete example
10694: 
10695: @cindex abstract class
10696: How do we create a graphical object? With the present definitions,
10697: we cannot create a useful graphical object. The class
10698: @code{graphical} describes graphical objects in general, but not
10699: any concrete graphical object type (C++ users would call it an
10700: @emph{abstract class}); e.g., there is no method for the selector
10701: @code{draw} in the class @code{graphical}.
10702: 
10703: For concrete graphical objects, we define child classes of the
10704: class @code{graphical}, e.g.:
10705: 
10706: @cindex @code{overrides} usage
10707: @cindex @code{field} usage in class definition
10708: @example
10709: graphical class \ "graphical" is the parent class
10710:   cell% field circle-radius
10711: 
10712: :noname ( x y circle -- )
10713:   circle-radius @@ draw-circle ;
10714: overrides draw
10715: 
10716: :noname ( n-radius circle -- )
10717:   circle-radius ! ;
10718: overrides construct
10719: 
10720: end-class circle
10721: @end example
10722: 
10723: Here we define a class @code{circle} as a child of @code{graphical},
10724: with field @code{circle-radius} (which behaves just like a field
10725: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10726: for the selectors @code{draw} and @code{construct} (@code{construct} is
10727: defined in @code{object}, the parent class of @code{graphical}).
10728: 
10729: Now we can create a circle on the heap (i.e.,
10730: @code{allocate}d memory) with:
10731: 
10732: @cindex @code{heap-new} usage
10733: @example
10734: 50 circle heap-new constant my-circle
10735: @end example
10736: 
10737: @noindent
10738: @code{heap-new} invokes @code{construct}, thus
10739: initializing the field @code{circle-radius} with 50. We can draw
10740: this new circle at (100,100) with:
10741: 
10742: @example
10743: 100 100 my-circle draw
10744: @end example
10745: 
10746: @cindex selector invocation, restrictions
10747: @cindex class definition, restrictions
10748: Note: You can only invoke a selector if the object on the TOS
10749: (the receiving object) belongs to the class where the selector was
10750: defined or one of its descendents; e.g., you can invoke
10751: @code{draw} only for objects belonging to @code{graphical}
10752: or its descendents (e.g., @code{circle}).  Immediately before
10753: @code{end-class}, the search order has to be the same as
10754: immediately after @code{class}.
10755: 
10756: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10757: @subsubsection The @file{object.fs} base class
10758: @cindex @code{object} class
10759: 
10760: When you define a class, you have to specify a parent class.  So how do
10761: you start defining classes? There is one class available from the start:
10762: @code{object}. It is ancestor for all classes and so is the
10763: only class that has no parent. It has two selectors: @code{construct}
10764: and @code{print}.
10765: 
10766: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10767: @subsubsection Creating objects
10768: @cindex creating objects
10769: @cindex object creation
10770: @cindex object allocation options
10771: 
10772: @cindex @code{heap-new} discussion
10773: @cindex @code{dict-new} discussion
10774: @cindex @code{construct} discussion
10775: You can create and initialize an object of a class on the heap with
10776: @code{heap-new} ( ... class -- object ) and in the dictionary
10777: (allocation with @code{allot}) with @code{dict-new} (
10778: ... class -- object ). Both words invoke @code{construct}, which
10779: consumes the stack items indicated by "..." above.
10780: 
10781: @cindex @code{init-object} discussion
10782: @cindex @code{class-inst-size} discussion
10783: If you want to allocate memory for an object yourself, you can get its
10784: alignment and size with @code{class-inst-size 2@@} ( class --
10785: align size ). Once you have memory for an object, you can initialize
10786: it with @code{init-object} ( ... class object -- );
10787: @code{construct} does only a part of the necessary work.
10788: 
10789: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10790: @subsubsection Object-Oriented Programming Style
10791: @cindex object-oriented programming style
10792: @cindex programming style, object-oriented
10793: 
10794: This section is not exhaustive.
10795: 
10796: @cindex stack effects of selectors
10797: @cindex selectors and stack effects
10798: In general, it is a good idea to ensure that all methods for the
10799: same selector have the same stack effect: when you invoke a selector,
10800: you often have no idea which method will be invoked, so, unless all
10801: methods have the same stack effect, you will not know the stack effect
10802: of the selector invocation.
10803: 
10804: One exception to this rule is methods for the selector
10805: @code{construct}. We know which method is invoked, because we
10806: specify the class to be constructed at the same place. Actually, I
10807: defined @code{construct} as a selector only to give the users a
10808: convenient way to specify initialization. The way it is used, a
10809: mechanism different from selector invocation would be more natural
10810: (but probably would take more code and more space to explain).
10811: 
10812: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10813: @subsubsection Class Binding
10814: @cindex class binding
10815: @cindex early binding
10816: 
10817: @cindex late binding
10818: Normal selector invocations determine the method at run-time depending
10819: on the class of the receiving object. This run-time selection is called
10820: @i{late binding}.
10821: 
10822: Sometimes it's preferable to invoke a different method. For example,
10823: you might want to use the simple method for @code{print}ing
10824: @code{object}s instead of the possibly long-winded @code{print} method
10825: of the receiver class. You can achieve this by replacing the invocation
10826: of @code{print} with:
10827: 
10828: @cindex @code{[bind]} usage
10829: @example
10830: [bind] object print
10831: @end example
10832: 
10833: @noindent
10834: in compiled code or:
10835: 
10836: @cindex @code{bind} usage
10837: @example
10838: bind object print
10839: @end example
10840: 
10841: @cindex class binding, alternative to
10842: @noindent
10843: in interpreted code. Alternatively, you can define the method with a
10844: name (e.g., @code{print-object}), and then invoke it through the
10845: name. Class binding is just a (often more convenient) way to achieve
10846: the same effect; it avoids name clutter and allows you to invoke
10847: methods directly without naming them first.
10848: 
10849: @cindex superclass binding
10850: @cindex parent class binding
10851: A frequent use of class binding is this: When we define a method
10852: for a selector, we often want the method to do what the selector does
10853: in the parent class, and a little more. There is a special word for
10854: this purpose: @code{[parent]}; @code{[parent]
10855: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10856: selector}}, where @code{@emph{parent}} is the parent
10857: class of the current class. E.g., a method definition might look like:
10858: 
10859: @cindex @code{[parent]} usage
10860: @example
10861: :noname
10862:   dup [parent] foo \ do parent's foo on the receiving object
10863:   ... \ do some more
10864: ; overrides foo
10865: @end example
10866: 
10867: @cindex class binding as optimization
10868: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10869: March 1997), Andrew McKewan presents class binding as an optimization
10870: technique. I recommend not using it for this purpose unless you are in
10871: an emergency. Late binding is pretty fast with this model anyway, so the
10872: benefit of using class binding is small; the cost of using class binding
10873: where it is not appropriate is reduced maintainability.
10874: 
10875: While we are at programming style questions: You should bind
10876: selectors only to ancestor classes of the receiving object. E.g., say,
10877: you know that the receiving object is of class @code{foo} or its
10878: descendents; then you should bind only to @code{foo} and its
10879: ancestors.
10880: 
10881: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10882: @subsubsection Method conveniences
10883: @cindex method conveniences
10884: 
10885: In a method you usually access the receiving object pretty often.  If
10886: you define the method as a plain colon definition (e.g., with
10887: @code{:noname}), you may have to do a lot of stack
10888: gymnastics. To avoid this, you can define the method with @code{m:
10889: ... ;m}. E.g., you could define the method for
10890: @code{draw}ing a @code{circle} with
10891: 
10892: @cindex @code{this} usage
10893: @cindex @code{m:} usage
10894: @cindex @code{;m} usage
10895: @example
10896: m: ( x y circle -- )
10897:   ( x y ) this circle-radius @@ draw-circle ;m
10898: @end example
10899: 
10900: @cindex @code{exit} in @code{m: ... ;m}
10901: @cindex @code{exitm} discussion
10902: @cindex @code{catch} in @code{m: ... ;m}
10903: When this method is executed, the receiver object is removed from the
10904: stack; you can access it with @code{this} (admittedly, in this
10905: example the use of @code{m: ... ;m} offers no advantage). Note
10906: that I specify the stack effect for the whole method (i.e. including
10907: the receiver object), not just for the code between @code{m:}
10908: and @code{;m}. You cannot use @code{exit} in
10909: @code{m:...;m}; instead, use
10910: @code{exitm}.@footnote{Moreover, for any word that calls
10911: @code{catch} and was defined before loading
10912: @code{objects.fs}, you have to redefine it like I redefined
10913: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10914: 
10915: @cindex @code{inst-var} usage
10916: You will frequently use sequences of the form @code{this
10917: @emph{field}} (in the example above: @code{this
10918: circle-radius}). If you use the field only in this way, you can
10919: define it with @code{inst-var} and eliminate the
10920: @code{this} before the field name. E.g., the @code{circle}
10921: class above could also be defined with:
10922: 
10923: @example
10924: graphical class
10925:   cell% inst-var radius
10926: 
10927: m: ( x y circle -- )
10928:   radius @@ draw-circle ;m
10929: overrides draw
10930: 
10931: m: ( n-radius circle -- )
10932:   radius ! ;m
10933: overrides construct
10934: 
10935: end-class circle
10936: @end example
10937: 
10938: @code{radius} can only be used in @code{circle} and its
10939: descendent classes and inside @code{m:...;m}.
10940: 
10941: @cindex @code{inst-value} usage
10942: You can also define fields with @code{inst-value}, which is
10943: to @code{inst-var} what @code{value} is to
10944: @code{variable}.  You can change the value of such a field with
10945: @code{[to-inst]}.  E.g., we could also define the class
10946: @code{circle} like this:
10947: 
10948: @example
10949: graphical class
10950:   inst-value radius
10951: 
10952: m: ( x y circle -- )
10953:   radius draw-circle ;m
10954: overrides draw
10955: 
10956: m: ( n-radius circle -- )
10957:   [to-inst] radius ;m
10958: overrides construct
10959: 
10960: end-class circle
10961: @end example
10962: 
10963: @c !! :m is easy to confuse with m:.  Another name would be better.
10964: 
10965: @c Finally, you can define named methods with @code{:m}.  One use of this
10966: @c feature is the definition of words that occur only in one class and are
10967: @c not intended to be overridden, but which still need method context
10968: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10969: @c would be bound frequently, if defined anonymously.
10970: 
10971: 
10972: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10973: @subsubsection Classes and Scoping
10974: @cindex classes and scoping
10975: @cindex scoping and classes
10976: 
10977: Inheritance is frequent, unlike structure extension. This exacerbates
10978: the problem with the field name convention (@pxref{Structure Naming
10979: Convention}): One always has to remember in which class the field was
10980: originally defined; changing a part of the class structure would require
10981: changes for renaming in otherwise unaffected code.
10982: 
10983: @cindex @code{inst-var} visibility
10984: @cindex @code{inst-value} visibility
10985: To solve this problem, I added a scoping mechanism (which was not in my
10986: original charter): A field defined with @code{inst-var} (or
10987: @code{inst-value}) is visible only in the class where it is defined and in
10988: the descendent classes of this class.  Using such fields only makes
10989: sense in @code{m:}-defined methods in these classes anyway.
10990: 
10991: This scoping mechanism allows us to use the unadorned field name,
10992: because name clashes with unrelated words become much less likely.
10993: 
10994: @cindex @code{protected} discussion
10995: @cindex @code{private} discussion
10996: Once we have this mechanism, we can also use it for controlling the
10997: visibility of other words: All words defined after
10998: @code{protected} are visible only in the current class and its
10999: descendents. @code{public} restores the compilation
11000: (i.e. @code{current}) word list that was in effect before. If you
11001: have several @code{protected}s without an intervening
11002: @code{public} or @code{set-current}, @code{public}
11003: will restore the compilation word list in effect before the first of
11004: these @code{protected}s.
11005: 
11006: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
11007: @subsubsection Dividing classes
11008: @cindex Dividing classes
11009: @cindex @code{methods}...@code{end-methods}
11010: 
11011: You may want to do the definition of methods separate from the
11012: definition of the class, its selectors, fields, and instance variables,
11013: i.e., separate the implementation from the definition.  You can do this
11014: in the following way:
11015: 
11016: @example
11017: graphical class
11018:   inst-value radius
11019: end-class circle
11020: 
11021: ... \ do some other stuff
11022: 
11023: circle methods \ now we are ready
11024: 
11025: m: ( x y circle -- )
11026:   radius draw-circle ;m
11027: overrides draw
11028: 
11029: m: ( n-radius circle -- )
11030:   [to-inst] radius ;m
11031: overrides construct
11032: 
11033: end-methods
11034: @end example
11035: 
11036: You can use several @code{methods}...@code{end-methods} sections.  The
11037: only things you can do to the class in these sections are: defining
11038: methods, and overriding the class's selectors.  You must not define new
11039: selectors or fields.
11040: 
11041: Note that you often have to override a selector before using it.  In
11042: particular, you usually have to override @code{construct} with a new
11043: method before you can invoke @code{heap-new} and friends.  E.g., you
11044: must not create a circle before the @code{overrides construct} sequence
11045: in the example above.
11046: 
11047: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
11048: @subsubsection Object Interfaces
11049: @cindex object interfaces
11050: @cindex interfaces for objects
11051: 
11052: In this model you can only call selectors defined in the class of the
11053: receiving objects or in one of its ancestors. If you call a selector
11054: with a receiving object that is not in one of these classes, the
11055: result is undefined; if you are lucky, the program crashes
11056: immediately.
11057: 
11058: @cindex selectors common to hardly-related classes
11059: Now consider the case when you want to have a selector (or several)
11060: available in two classes: You would have to add the selector to a
11061: common ancestor class, in the worst case to @code{object}. You
11062: may not want to do this, e.g., because someone else is responsible for
11063: this ancestor class.
11064: 
11065: The solution for this problem is interfaces. An interface is a
11066: collection of selectors. If a class implements an interface, the
11067: selectors become available to the class and its descendents. A class
11068: can implement an unlimited number of interfaces. For the problem
11069: discussed above, we would define an interface for the selector(s), and
11070: both classes would implement the interface.
11071: 
11072: As an example, consider an interface @code{storage} for
11073: writing objects to disk and getting them back, and a class
11074: @code{foo} that implements it. The code would look like this:
11075: 
11076: @cindex @code{interface} usage
11077: @cindex @code{end-interface} usage
11078: @cindex @code{implementation} usage
11079: @example
11080: interface
11081:   selector write ( file object -- )
11082:   selector read1 ( file object -- )
11083: end-interface storage
11084: 
11085: bar class
11086:   storage implementation
11087: 
11088: ... overrides write
11089: ... overrides read1
11090: ...
11091: end-class foo
11092: @end example
11093: 
11094: @noindent
11095: (I would add a word @code{read} @i{( file -- object )} that uses
11096: @code{read1} internally, but that's beyond the point illustrated
11097: here.)
11098: 
11099: Note that you cannot use @code{protected} in an interface; and
11100: of course you cannot define fields.
11101: 
11102: In the Neon model, all selectors are available for all classes;
11103: therefore it does not need interfaces. The price you pay in this model
11104: is slower late binding, and therefore, added complexity to avoid late
11105: binding.
11106: 
11107: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
11108: @subsubsection @file{objects.fs} Implementation
11109: @cindex @file{objects.fs} implementation
11110: 
11111: @cindex @code{object-map} discussion
11112: An object is a piece of memory, like one of the data structures
11113: described with @code{struct...end-struct}. It has a field
11114: @code{object-map} that points to the method map for the object's
11115: class.
11116: 
11117: @cindex method map
11118: @cindex virtual function table
11119: The @emph{method map}@footnote{This is Self terminology; in C++
11120: terminology: virtual function table.} is an array that contains the
11121: execution tokens (@i{xt}s) of the methods for the object's class. Each
11122: selector contains an offset into a method map.
11123: 
11124: @cindex @code{selector} implementation, class
11125: @code{selector} is a defining word that uses
11126: @code{CREATE} and @code{DOES>}. The body of the
11127: selector contains the offset; the @code{DOES>} action for a
11128: class selector is, basically:
11129: 
11130: @example
11131: ( object addr ) @@ over object-map @@ + @@ execute
11132: @end example
11133: 
11134: Since @code{object-map} is the first field of the object, it
11135: does not generate any code. As you can see, calling a selector has a
11136: small, constant cost.
11137: 
11138: @cindex @code{current-interface} discussion
11139: @cindex class implementation and representation
11140: A class is basically a @code{struct} combined with a method
11141: map. During the class definition the alignment and size of the class
11142: are passed on the stack, just as with @code{struct}s, so
11143: @code{field} can also be used for defining class
11144: fields. However, passing more items on the stack would be
11145: inconvenient, so @code{class} builds a data structure in memory,
11146: which is accessed through the variable
11147: @code{current-interface}. After its definition is complete, the
11148: class is represented on the stack by a pointer (e.g., as parameter for
11149: a child class definition).
11150: 
11151: A new class starts off with the alignment and size of its parent,
11152: and a copy of the parent's method map. Defining new fields extends the
11153: size and alignment; likewise, defining new selectors extends the
11154: method map. @code{overrides} just stores a new @i{xt} in the method
11155: map at the offset given by the selector.
11156: 
11157: @cindex class binding, implementation
11158: Class binding just gets the @i{xt} at the offset given by the selector
11159: from the class's method map and @code{compile,}s (in the case of
11160: @code{[bind]}) it.
11161: 
11162: @cindex @code{this} implementation
11163: @cindex @code{catch} and @code{this}
11164: @cindex @code{this} and @code{catch}
11165: I implemented @code{this} as a @code{value}. At the
11166: start of an @code{m:...;m} method the old @code{this} is
11167: stored to the return stack and restored at the end; and the object on
11168: the TOS is stored @code{TO this}. This technique has one
11169: disadvantage: If the user does not leave the method via
11170: @code{;m}, but via @code{throw} or @code{exit},
11171: @code{this} is not restored (and @code{exit} may
11172: crash). To deal with the @code{throw} problem, I have redefined
11173: @code{catch} to save and restore @code{this}; the same
11174: should be done with any word that can catch an exception. As for
11175: @code{exit}, I simply forbid it (as a replacement, there is
11176: @code{exitm}).
11177: 
11178: @cindex @code{inst-var} implementation
11179: @code{inst-var} is just the same as @code{field}, with
11180: a different @code{DOES>} action:
11181: @example
11182: @@ this +
11183: @end example
11184: Similar for @code{inst-value}.
11185: 
11186: @cindex class scoping implementation
11187: Each class also has a word list that contains the words defined with
11188: @code{inst-var} and @code{inst-value}, and its protected
11189: words. It also has a pointer to its parent. @code{class} pushes
11190: the word lists of the class and all its ancestors onto the search order stack,
11191: and @code{end-class} drops them.
11192: 
11193: @cindex interface implementation
11194: An interface is like a class without fields, parent and protected
11195: words; i.e., it just has a method map. If a class implements an
11196: interface, its method map contains a pointer to the method map of the
11197: interface. The positive offsets in the map are reserved for class
11198: methods, therefore interface map pointers have negative
11199: offsets. Interfaces have offsets that are unique throughout the
11200: system, unlike class selectors, whose offsets are only unique for the
11201: classes where the selector is available (invokable).
11202: 
11203: This structure means that interface selectors have to perform one
11204: indirection more than class selectors to find their method. Their body
11205: contains the interface map pointer offset in the class method map, and
11206: the method offset in the interface method map. The
11207: @code{does>} action for an interface selector is, basically:
11208: 
11209: @example
11210: ( object selector-body )
11211: 2dup selector-interface @@ ( object selector-body object interface-offset )
11212: swap object-map @@ + @@ ( object selector-body map )
11213: swap selector-offset @@ + @@ execute
11214: @end example
11215: 
11216: where @code{object-map} and @code{selector-offset} are
11217: first fields and generate no code.
11218: 
11219: As a concrete example, consider the following code:
11220: 
11221: @example
11222: interface
11223:   selector if1sel1
11224:   selector if1sel2
11225: end-interface if1
11226: 
11227: object class
11228:   if1 implementation
11229:   selector cl1sel1
11230:   cell% inst-var cl1iv1
11231: 
11232: ' m1 overrides construct
11233: ' m2 overrides if1sel1
11234: ' m3 overrides if1sel2
11235: ' m4 overrides cl1sel2
11236: end-class cl1
11237: 
11238: create obj1 object dict-new drop
11239: create obj2 cl1    dict-new drop
11240: @end example
11241: 
11242: The data structure created by this code (including the data structure
11243: for @code{object}) is shown in the
11244: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11245: @comment TODO add this diagram..
11246: 
11247: @node Objects Glossary,  , Objects Implementation, Objects
11248: @subsubsection @file{objects.fs} Glossary
11249: @cindex @file{objects.fs} Glossary
11250: 
11251: 
11252: doc---objects-bind
11253: doc---objects-<bind>
11254: doc---objects-bind'
11255: doc---objects-[bind]
11256: doc---objects-class
11257: doc---objects-class->map
11258: doc---objects-class-inst-size
11259: doc---objects-class-override!
11260: doc---objects-class-previous
11261: doc---objects-class>order
11262: doc---objects-construct
11263: doc---objects-current'
11264: doc---objects-[current]
11265: doc---objects-current-interface
11266: doc---objects-dict-new
11267: doc---objects-end-class
11268: doc---objects-end-class-noname
11269: doc---objects-end-interface
11270: doc---objects-end-interface-noname
11271: doc---objects-end-methods
11272: doc---objects-exitm
11273: doc---objects-heap-new
11274: doc---objects-implementation
11275: doc---objects-init-object
11276: doc---objects-inst-value
11277: doc---objects-inst-var
11278: doc---objects-interface
11279: doc---objects-m:
11280: doc---objects-:m
11281: doc---objects-;m
11282: doc---objects-method
11283: doc---objects-methods
11284: doc---objects-object
11285: doc---objects-overrides
11286: doc---objects-[parent]
11287: doc---objects-print
11288: doc---objects-protected
11289: doc---objects-public
11290: doc---objects-selector
11291: doc---objects-this
11292: doc---objects-<to-inst>
11293: doc---objects-[to-inst]
11294: doc---objects-to-this
11295: doc---objects-xt-new
11296: 
11297: 
11298: @c -------------------------------------------------------------
11299: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11300: @subsection The @file{oof.fs} model
11301: @cindex oof
11302: @cindex object-oriented programming
11303: 
11304: @cindex @file{objects.fs}
11305: @cindex @file{oof.fs}
11306: 
11307: This section describes the @file{oof.fs} package.
11308: 
11309: The package described in this section has been used in bigFORTH since 1991, and
11310: used for two large applications: a chromatographic system used to
11311: create new medicaments, and a graphic user interface library (MINOS).
11312: 
11313: You can find a description (in German) of @file{oof.fs} in @cite{Object
11314: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11315: 10(2), 1994.
11316: 
11317: @menu
11318: * Properties of the OOF model::  
11319: * Basic OOF Usage::             
11320: * The OOF base class::          
11321: * Class Declaration::           
11322: * Class Implementation::        
11323: @end menu
11324: 
11325: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11326: @subsubsection Properties of the @file{oof.fs} model
11327: @cindex @file{oof.fs} properties
11328: 
11329: @itemize @bullet
11330: @item
11331: This model combines object oriented programming with information
11332: hiding. It helps you writing large application, where scoping is
11333: necessary, because it provides class-oriented scoping.
11334: 
11335: @item
11336: Named objects, object pointers, and object arrays can be created,
11337: selector invocation uses the ``object selector'' syntax. Selector invocation
11338: to objects and/or selectors on the stack is a bit less convenient, but
11339: possible.
11340: 
11341: @item
11342: Selector invocation and instance variable usage of the active object is
11343: straightforward, since both make use of the active object.
11344: 
11345: @item
11346: Late binding is efficient and easy to use.
11347: 
11348: @item
11349: State-smart objects parse selectors. However, extensibility is provided
11350: using a (parsing) selector @code{postpone} and a selector @code{'}.
11351: 
11352: @item
11353: An implementation in ANS Forth is available.
11354: 
11355: @end itemize
11356: 
11357: 
11358: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11359: @subsubsection Basic @file{oof.fs} Usage
11360: @cindex @file{oof.fs} usage
11361: 
11362: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
11363: 
11364: You can define a class for graphical objects like this:
11365: 
11366: @cindex @code{class} usage
11367: @cindex @code{class;} usage
11368: @cindex @code{method} usage
11369: @example
11370: object class graphical \ "object" is the parent class
11371:   method draw ( x y -- )
11372: class;
11373: @end example
11374: 
11375: This code defines a class @code{graphical} with an
11376: operation @code{draw}.  We can perform the operation
11377: @code{draw} on any @code{graphical} object, e.g.:
11378: 
11379: @example
11380: 100 100 t-rex draw
11381: @end example
11382: 
11383: @noindent
11384: where @code{t-rex} is an object or object pointer, created with e.g.
11385: @code{graphical : t-rex}.
11386: 
11387: @cindex abstract class
11388: How do we create a graphical object? With the present definitions,
11389: we cannot create a useful graphical object. The class
11390: @code{graphical} describes graphical objects in general, but not
11391: any concrete graphical object type (C++ users would call it an
11392: @emph{abstract class}); e.g., there is no method for the selector
11393: @code{draw} in the class @code{graphical}.
11394: 
11395: For concrete graphical objects, we define child classes of the
11396: class @code{graphical}, e.g.:
11397: 
11398: @example
11399: graphical class circle \ "graphical" is the parent class
11400:   cell var circle-radius
11401: how:
11402:   : draw ( x y -- )
11403:     circle-radius @@ draw-circle ;
11404: 
11405:   : init ( n-radius -- )
11406:     circle-radius ! ;
11407: class;
11408: @end example
11409: 
11410: Here we define a class @code{circle} as a child of @code{graphical},
11411: with a field @code{circle-radius}; it defines new methods for the
11412: selectors @code{draw} and @code{init} (@code{init} is defined in
11413: @code{object}, the parent class of @code{graphical}).
11414: 
11415: Now we can create a circle in the dictionary with:
11416: 
11417: @example
11418: 50 circle : my-circle
11419: @end example
11420: 
11421: @noindent
11422: @code{:} invokes @code{init}, thus initializing the field
11423: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11424: with:
11425: 
11426: @example
11427: 100 100 my-circle draw
11428: @end example
11429: 
11430: @cindex selector invocation, restrictions
11431: @cindex class definition, restrictions
11432: Note: You can only invoke a selector if the receiving object belongs to
11433: the class where the selector was defined or one of its descendents;
11434: e.g., you can invoke @code{draw} only for objects belonging to
11435: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11436: mechanism will check if you try to invoke a selector that is not
11437: defined in this class hierarchy, so you'll get an error at compilation
11438: time.
11439: 
11440: 
11441: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11442: @subsubsection The @file{oof.fs} base class
11443: @cindex @file{oof.fs} base class
11444: 
11445: When you define a class, you have to specify a parent class.  So how do
11446: you start defining classes? There is one class available from the start:
11447: @code{object}. You have to use it as ancestor for all classes. It is the
11448: only class that has no parent. Classes are also objects, except that
11449: they don't have instance variables; class manipulation such as
11450: inheritance or changing definitions of a class is handled through
11451: selectors of the class @code{object}.
11452: 
11453: @code{object} provides a number of selectors:
11454: 
11455: @itemize @bullet
11456: @item
11457: @code{class} for subclassing, @code{definitions} to add definitions
11458: later on, and @code{class?} to get type informations (is the class a
11459: subclass of the class passed on the stack?).
11460: 
11461: doc---object-class
11462: doc---object-definitions
11463: doc---object-class?
11464: 
11465: 
11466: @item
11467: @code{init} and @code{dispose} as constructor and destructor of the
11468: object. @code{init} is invocated after the object's memory is allocated,
11469: while @code{dispose} also handles deallocation. Thus if you redefine
11470: @code{dispose}, you have to call the parent's dispose with @code{super
11471: dispose}, too.
11472: 
11473: doc---object-init
11474: doc---object-dispose
11475: 
11476: 
11477: @item
11478: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11479: @code{[]} to create named and unnamed objects and object arrays or
11480: object pointers.
11481: 
11482: doc---object-new
11483: doc---object-new[]
11484: doc---object-:
11485: doc---object-ptr
11486: doc---object-asptr
11487: doc---object-[]
11488: 
11489: 
11490: @item
11491: @code{::} and @code{super} for explicit scoping. You should use explicit
11492: scoping only for super classes or classes with the same set of instance
11493: variables. Explicitly-scoped selectors use early binding.
11494: 
11495: doc---object-::
11496: doc---object-super
11497: 
11498: 
11499: @item
11500: @code{self} to get the address of the object
11501: 
11502: doc---object-self
11503: 
11504: 
11505: @item
11506: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11507: pointers and instance defers.
11508: 
11509: doc---object-bind
11510: doc---object-bound
11511: doc---object-link
11512: doc---object-is
11513: 
11514: 
11515: @item
11516: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11517: form the stack, and @code{postpone} to generate selector invocation code.
11518: 
11519: doc---object-'
11520: doc---object-postpone
11521: 
11522: 
11523: @item
11524: @code{with} and @code{endwith} to select the active object from the
11525: stack, and enable its scope. Using @code{with} and @code{endwith}
11526: also allows you to create code using selector @code{postpone} without being
11527: trapped by the state-smart objects.
11528: 
11529: doc---object-with
11530: doc---object-endwith
11531: 
11532: 
11533: @end itemize
11534: 
11535: @node Class Declaration, Class Implementation, The OOF base class, OOF
11536: @subsubsection Class Declaration
11537: @cindex class declaration
11538: 
11539: @itemize @bullet
11540: @item
11541: Instance variables
11542: 
11543: doc---oof-var
11544: 
11545: 
11546: @item
11547: Object pointers
11548: 
11549: doc---oof-ptr
11550: doc---oof-asptr
11551: 
11552: 
11553: @item
11554: Instance defers
11555: 
11556: doc---oof-defer
11557: 
11558: 
11559: @item
11560: Method selectors
11561: 
11562: doc---oof-early
11563: doc---oof-method
11564: 
11565: 
11566: @item
11567: Class-wide variables
11568: 
11569: doc---oof-static
11570: 
11571: 
11572: @item
11573: End declaration
11574: 
11575: doc---oof-how:
11576: doc---oof-class;
11577: 
11578: 
11579: @end itemize
11580: 
11581: @c -------------------------------------------------------------
11582: @node Class Implementation,  , Class Declaration, OOF
11583: @subsubsection Class Implementation
11584: @cindex class implementation
11585: 
11586: @c -------------------------------------------------------------
11587: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11588: @subsection The @file{mini-oof.fs} model
11589: @cindex mini-oof
11590: 
11591: Gforth's third object oriented Forth package is a 12-liner. It uses a
11592: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11593: and reduces to the bare minimum of features. This is based on a posting
11594: of Bernd Paysan in comp.lang.forth.
11595: 
11596: @menu
11597: * Basic Mini-OOF Usage::        
11598: * Mini-OOF Example::            
11599: * Mini-OOF Implementation::     
11600: @end menu
11601: 
11602: @c -------------------------------------------------------------
11603: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11604: @subsubsection Basic @file{mini-oof.fs} Usage
11605: @cindex mini-oof usage
11606: 
11607: There is a base class (@code{class}, which allocates one cell for the
11608: object pointer) plus seven other words: to define a method, a variable,
11609: a class; to end a class, to resolve binding, to allocate an object and
11610: to compile a class method.
11611: @comment TODO better description of the last one
11612: 
11613: 
11614: doc-object
11615: doc-method
11616: doc-var
11617: doc-class
11618: doc-end-class
11619: doc-defines
11620: doc-new
11621: doc-::
11622: 
11623: 
11624: 
11625: @c -------------------------------------------------------------
11626: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11627: @subsubsection Mini-OOF Example
11628: @cindex mini-oof example
11629: 
11630: A short example shows how to use this package. This example, in slightly
11631: extended form, is supplied as @file{moof-exm.fs}
11632: @comment TODO could flesh this out with some comments from the Forthwrite article
11633: 
11634: @example
11635: object class
11636:   method init
11637:   method draw
11638: end-class graphical
11639: @end example
11640: 
11641: This code defines a class @code{graphical} with an
11642: operation @code{draw}.  We can perform the operation
11643: @code{draw} on any @code{graphical} object, e.g.:
11644: 
11645: @example
11646: 100 100 t-rex draw
11647: @end example
11648: 
11649: where @code{t-rex} is an object or object pointer, created with e.g.
11650: @code{graphical new Constant t-rex}.
11651: 
11652: For concrete graphical objects, we define child classes of the
11653: class @code{graphical}, e.g.:
11654: 
11655: @example
11656: graphical class
11657:   cell var circle-radius
11658: end-class circle \ "graphical" is the parent class
11659: 
11660: :noname ( x y -- )
11661:   circle-radius @@ draw-circle ; circle defines draw
11662: :noname ( r -- )
11663:   circle-radius ! ; circle defines init
11664: @end example
11665: 
11666: There is no implicit init method, so we have to define one. The creation
11667: code of the object now has to call init explicitely.
11668: 
11669: @example
11670: circle new Constant my-circle
11671: 50 my-circle init
11672: @end example
11673: 
11674: It is also possible to add a function to create named objects with
11675: automatic call of @code{init}, given that all objects have @code{init}
11676: on the same place:
11677: 
11678: @example
11679: : new: ( .. o "name" -- )
11680:     new dup Constant init ;
11681: 80 circle new: large-circle
11682: @end example
11683: 
11684: We can draw this new circle at (100,100) with:
11685: 
11686: @example
11687: 100 100 my-circle draw
11688: @end example
11689: 
11690: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11691: @subsubsection @file{mini-oof.fs} Implementation
11692: 
11693: Object-oriented systems with late binding typically use a
11694: ``vtable''-approach: the first variable in each object is a pointer to a
11695: table, which contains the methods as function pointers. The vtable
11696: may also contain other information.
11697: 
11698: So first, let's declare selectors:
11699: 
11700: @example
11701: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11702:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11703: @end example
11704: 
11705: During selector declaration, the number of selectors and instance
11706: variables is on the stack (in address units). @code{method} creates one
11707: selector and increments the selector number. To execute a selector, it
11708: takes the object, fetches the vtable pointer, adds the offset, and
11709: executes the method @i{xt} stored there. Each selector takes the object
11710: it is invoked with as top of stack parameter; it passes the parameters
11711: (including the object) unchanged to the appropriate method which should
11712: consume that object.
11713: 
11714: Now, we also have to declare instance variables
11715: 
11716: @example
11717: : var ( m v size "name" -- m v' ) Create  over , +
11718:   DOES> ( o -- addr ) @@ + ;
11719: @end example
11720: 
11721: As before, a word is created with the current offset. Instance
11722: variables can have different sizes (cells, floats, doubles, chars), so
11723: all we do is take the size and add it to the offset. If your machine
11724: has alignment restrictions, put the proper @code{aligned} or
11725: @code{faligned} before the variable, to adjust the variable
11726: offset. That's why it is on the top of stack.
11727: 
11728: We need a starting point (the base object) and some syntactic sugar:
11729: 
11730: @example
11731: Create object  1 cells , 2 cells ,
11732: : class ( class -- class selectors vars ) dup 2@@ ;
11733: @end example
11734: 
11735: For inheritance, the vtable of the parent object has to be
11736: copied when a new, derived class is declared. This gives all the
11737: methods of the parent class, which can be overridden, though.
11738: 
11739: @example
11740: : end-class  ( class selectors vars "name" -- )
11741:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11742:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11743: @end example
11744: 
11745: The first line creates the vtable, initialized with
11746: @code{noop}s. The second line is the inheritance mechanism, it
11747: copies the xts from the parent vtable.
11748: 
11749: We still have no way to define new methods, let's do that now:
11750: 
11751: @example
11752: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11753: @end example
11754: 
11755: To allocate a new object, we need a word, too:
11756: 
11757: @example
11758: : new ( class -- o )  here over @@ allot swap over ! ;
11759: @end example
11760: 
11761: Sometimes derived classes want to access the method of the
11762: parent object. There are two ways to achieve this with Mini-OOF:
11763: first, you could use named words, and second, you could look up the
11764: vtable of the parent object.
11765: 
11766: @example
11767: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11768: @end example
11769: 
11770: 
11771: Nothing can be more confusing than a good example, so here is
11772: one. First let's declare a text object (called
11773: @code{button}), that stores text and position:
11774: 
11775: @example
11776: object class
11777:   cell var text
11778:   cell var len
11779:   cell var x
11780:   cell var y
11781:   method init
11782:   method draw
11783: end-class button
11784: @end example
11785: 
11786: @noindent
11787: Now, implement the two methods, @code{draw} and @code{init}:
11788: 
11789: @example
11790: :noname ( o -- )
11791:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11792:  button defines draw
11793: :noname ( addr u o -- )
11794:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11795:  button defines init
11796: @end example
11797: 
11798: @noindent
11799: To demonstrate inheritance, we define a class @code{bold-button}, with no
11800: new data and no new selectors:
11801: 
11802: @example
11803: button class
11804: end-class bold-button
11805: 
11806: : bold   27 emit ." [1m" ;
11807: : normal 27 emit ." [0m" ;
11808: @end example
11809: 
11810: @noindent
11811: The class @code{bold-button} has a different draw method to
11812: @code{button}, but the new method is defined in terms of the draw method
11813: for @code{button}:
11814: 
11815: @example
11816: :noname bold [ button :: draw ] normal ; bold-button defines draw
11817: @end example
11818: 
11819: @noindent
11820: Finally, create two objects and apply selectors:
11821: 
11822: @example
11823: button new Constant foo
11824: s" thin foo" foo init
11825: page
11826: foo draw
11827: bold-button new Constant bar
11828: s" fat bar" bar init
11829: 1 bar y !
11830: bar draw
11831: @end example
11832: 
11833: 
11834: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11835: @subsection Comparison with other object models
11836: @cindex comparison of object models
11837: @cindex object models, comparison
11838: 
11839: Many object-oriented Forth extensions have been proposed (@cite{A survey
11840: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11841: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11842: relation of the object models described here to two well-known and two
11843: closely-related (by the use of method maps) models.  Andras Zsoter
11844: helped us with this section.
11845: 
11846: @cindex Neon model
11847: The most popular model currently seems to be the Neon model (see
11848: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11849: 1997) by Andrew McKewan) but this model has a number of limitations
11850: @footnote{A longer version of this critique can be
11851: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11852: Dimensions, May 1997) by Anton Ertl.}:
11853: 
11854: @itemize @bullet
11855: @item
11856: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11857: to pass objects on the stack.
11858: 
11859: @item
11860: It requires that the selector parses the input stream (at
11861: compile time); this leads to reduced extensibility and to bugs that are
11862: hard to find.
11863: 
11864: @item
11865: It allows using every selector on every object; this eliminates the
11866: need for interfaces, but makes it harder to create efficient
11867: implementations.
11868: @end itemize
11869: 
11870: @cindex Pountain's object-oriented model
11871: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11872: Press, London, 1987) by Dick Pountain. However, it is not really about
11873: object-oriented programming, because it hardly deals with late
11874: binding. Instead, it focuses on features like information hiding and
11875: overloading that are characteristic of modular languages like Ada (83).
11876: 
11877: @cindex Zsoter's object-oriented model
11878: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11879: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11880: describes a model that makes heavy use of an active object (like
11881: @code{this} in @file{objects.fs}): The active object is not only used
11882: for accessing all fields, but also specifies the receiving object of
11883: every selector invocation; you have to change the active object
11884: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11885: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11886: the method entry point is unnecessary with Zsoter's model, because the
11887: receiving object is the active object already. On the other hand, the
11888: explicit change is absolutely necessary in that model, because otherwise
11889: no one could ever change the active object. An ANS Forth implementation
11890: of this model is available through
11891: @uref{http://www.forth.org/oopf.html}.
11892: 
11893: @cindex @file{oof.fs}, differences to other models
11894: The @file{oof.fs} model combines information hiding and overloading
11895: resolution (by keeping names in various word lists) with object-oriented
11896: programming. It sets the active object implicitly on method entry, but
11897: also allows explicit changing (with @code{>o...o>} or with
11898: @code{with...endwith}). It uses parsing and state-smart objects and
11899: classes for resolving overloading and for early binding: the object or
11900: class parses the selector and determines the method from this. If the
11901: selector is not parsed by an object or class, it performs a call to the
11902: selector for the active object (late binding), like Zsoter's model.
11903: Fields are always accessed through the active object. The big
11904: disadvantage of this model is the parsing and the state-smartness, which
11905: reduces extensibility and increases the opportunities for subtle bugs;
11906: essentially, you are only safe if you never tick or @code{postpone} an
11907: object or class (Bernd disagrees, but I (Anton) am not convinced).
11908: 
11909: @cindex @file{mini-oof.fs}, differences to other models
11910: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11911: version of the @file{objects.fs} model, but syntactically it is a
11912: mixture of the @file{objects.fs} and @file{oof.fs} models.
11913: 
11914: 
11915: @c -------------------------------------------------------------
11916: @node Programming Tools, C Interface, Object-oriented Forth, Words
11917: @section Programming Tools
11918: @cindex programming tools
11919: 
11920: @c !! move this and assembler down below OO stuff.
11921: 
11922: @menu
11923: * Examining::                   Data and Code.
11924: * Forgetting words::            Usually before reloading.
11925: * Debugging::                   Simple and quick.
11926: * Assertions::                  Making your programs self-checking.
11927: * Singlestep Debugger::         Executing your program word by word.
11928: @end menu
11929: 
11930: @node Examining, Forgetting words, Programming Tools, Programming Tools
11931: @subsection Examining data and code
11932: @cindex examining data and code
11933: @cindex data examination
11934: @cindex code examination
11935: 
11936: The following words inspect the stack non-destructively:
11937: 
11938: doc-.s
11939: doc-f.s
11940: doc-maxdepth-.s
11941: 
11942: There is a word @code{.r} but it does @i{not} display the return stack!
11943: It is used for formatted numeric output (@pxref{Simple numeric output}).
11944: 
11945: doc-depth
11946: doc-fdepth
11947: doc-clearstack
11948: doc-clearstacks
11949: 
11950: The following words inspect memory.
11951: 
11952: doc-?
11953: doc-dump
11954: 
11955: And finally, @code{see} allows to inspect code:
11956: 
11957: doc-see
11958: doc-xt-see
11959: doc-simple-see
11960: doc-simple-see-range
11961: doc-see-code
11962: doc-see-code-range
11963: 
11964: @node Forgetting words, Debugging, Examining, Programming Tools
11965: @subsection Forgetting words
11966: @cindex words, forgetting
11967: @cindex forgeting words
11968: 
11969: @c  anton: other, maybe better places for this subsection: Defining Words;
11970: @c  Dictionary allocation.  At least a reference should be there.
11971: 
11972: Forth allows you to forget words (and everything that was alloted in the
11973: dictonary after them) in a LIFO manner.
11974: 
11975: doc-marker
11976: 
11977: The most common use of this feature is during progam development: when
11978: you change a source file, forget all the words it defined and load it
11979: again (since you also forget everything defined after the source file
11980: was loaded, you have to reload that, too).  Note that effects like
11981: storing to variables and destroyed system words are not undone when you
11982: forget words.  With a system like Gforth, that is fast enough at
11983: starting up and compiling, I find it more convenient to exit and restart
11984: Gforth, as this gives me a clean slate.
11985: 
11986: Here's an example of using @code{marker} at the start of a source file
11987: that you are debugging; it ensures that you only ever have one copy of
11988: the file's definitions compiled at any time:
11989: 
11990: @example
11991: [IFDEF] my-code
11992:     my-code
11993: [ENDIF]
11994: 
11995: marker my-code
11996: init-included-files
11997: 
11998: \ .. definitions start here
11999: \ .
12000: \ .
12001: \ end
12002: @end example
12003: 
12004: 
12005: @node Debugging, Assertions, Forgetting words, Programming Tools
12006: @subsection Debugging
12007: @cindex debugging
12008: 
12009: Languages with a slow edit/compile/link/test development loop tend to
12010: require sophisticated tracing/stepping debuggers to facilate debugging.
12011: 
12012: A much better (faster) way in fast-compiling languages is to add
12013: printing code at well-selected places, let the program run, look at
12014: the output, see where things went wrong, add more printing code, etc.,
12015: until the bug is found.
12016: 
12017: The simple debugging aids provided in @file{debugs.fs}
12018: are meant to support this style of debugging.
12019: 
12020: The word @code{~~} prints debugging information (by default the source
12021: location and the stack contents). It is easy to insert. If you use Emacs
12022: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
12023: query-replace them with nothing). The deferred words
12024: @code{printdebugdata} and @code{.debugline} control the output of
12025: @code{~~}. The default source location output format works well with
12026: Emacs' compilation mode, so you can step through the program at the
12027: source level using @kbd{C-x `} (the advantage over a stepping debugger
12028: is that you can step in any direction and you know where the crash has
12029: happened or where the strange data has occurred).
12030: 
12031: doc-~~
12032: doc-printdebugdata
12033: doc-.debugline
12034: doc-debug-fid
12035: 
12036: @cindex filenames in @code{~~} output
12037: @code{~~} (and assertions) will usually print the wrong file name if a
12038: marker is executed in the same file after their occurance.  They will
12039: print @samp{*somewhere*} as file name if a marker is executed in the
12040: same file before their occurance.
12041: 
12042: 
12043: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
12044: @subsection Assertions
12045: @cindex assertions
12046: 
12047: It is a good idea to make your programs self-checking, especially if you
12048: make an assumption that may become invalid during maintenance (for
12049: example, that a certain field of a data structure is never zero). Gforth
12050: supports @dfn{assertions} for this purpose. They are used like this:
12051: 
12052: @example
12053: assert( @i{flag} )
12054: @end example
12055: 
12056: The code between @code{assert(} and @code{)} should compute a flag, that
12057: should be true if everything is alright and false otherwise. It should
12058: not change anything else on the stack. The overall stack effect of the
12059: assertion is @code{( -- )}. E.g.
12060: 
12061: @example
12062: assert( 1 1 + 2 = ) \ what we learn in school
12063: assert( dup 0<> ) \ assert that the top of stack is not zero
12064: assert( false ) \ this code should not be reached
12065: @end example
12066: 
12067: The need for assertions is different at different times. During
12068: debugging, we want more checking, in production we sometimes care more
12069: for speed. Therefore, assertions can be turned off, i.e., the assertion
12070: becomes a comment. Depending on the importance of an assertion and the
12071: time it takes to check it, you may want to turn off some assertions and
12072: keep others turned on. Gforth provides several levels of assertions for
12073: this purpose:
12074: 
12075: 
12076: doc-assert0(
12077: doc-assert1(
12078: doc-assert2(
12079: doc-assert3(
12080: doc-assert(
12081: doc-)
12082: 
12083: 
12084: The variable @code{assert-level} specifies the highest assertions that
12085: are turned on. I.e., at the default @code{assert-level} of one,
12086: @code{assert0(} and @code{assert1(} assertions perform checking, while
12087: @code{assert2(} and @code{assert3(} assertions are treated as comments.
12088: 
12089: The value of @code{assert-level} is evaluated at compile-time, not at
12090: run-time. Therefore you cannot turn assertions on or off at run-time;
12091: you have to set the @code{assert-level} appropriately before compiling a
12092: piece of code. You can compile different pieces of code at different
12093: @code{assert-level}s (e.g., a trusted library at level 1 and
12094: newly-written code at level 3).
12095: 
12096: 
12097: doc-assert-level
12098: 
12099: 
12100: If an assertion fails, a message compatible with Emacs' compilation mode
12101: is produced and the execution is aborted (currently with @code{ABORT"}.
12102: If there is interest, we will introduce a special throw code. But if you
12103: intend to @code{catch} a specific condition, using @code{throw} is
12104: probably more appropriate than an assertion).
12105: 
12106: @cindex filenames in assertion output
12107: Assertions (and @code{~~}) will usually print the wrong file name if a
12108: marker is executed in the same file after their occurance.  They will
12109: print @samp{*somewhere*} as file name if a marker is executed in the
12110: same file before their occurance.
12111: 
12112: Definitions in ANS Forth for these assertion words are provided
12113: in @file{compat/assert.fs}.
12114: 
12115: 
12116: @node Singlestep Debugger,  , Assertions, Programming Tools
12117: @subsection Singlestep Debugger
12118: @cindex singlestep Debugger
12119: @cindex debugging Singlestep
12120: 
12121: The singlestep debugger works only with the engine @code{gforth-itc}.
12122: 
12123: When you create a new word there's often the need to check whether it
12124: behaves correctly or not. You can do this by typing @code{dbg
12125: badword}. A debug session might look like this:
12126: 
12127: @example
12128: : badword 0 DO i . LOOP ;  ok
12129: 2 dbg badword 
12130: : badword  
12131: Scanning code...
12132: 
12133: Nesting debugger ready!
12134: 
12135: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
12136: 400D4740  8049F68 DO             -> [ 0 ] 
12137: 400D4744  804A0C8 i              -> [ 1 ] 00000 
12138: 400D4748 400C5E60 .              -> 0 [ 0 ] 
12139: 400D474C  8049D0C LOOP           -> [ 0 ] 
12140: 400D4744  804A0C8 i              -> [ 1 ] 00001 
12141: 400D4748 400C5E60 .              -> 1 [ 0 ] 
12142: 400D474C  8049D0C LOOP           -> [ 0 ] 
12143: 400D4758  804B384 ;              ->  ok
12144: @end example
12145: 
12146: Each line displayed is one step. You always have to hit return to
12147: execute the next word that is displayed. If you don't want to execute
12148: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12149: an overview what keys are available:
12150: 
12151: @table @i
12152: 
12153: @item @key{RET}
12154: Next; Execute the next word.
12155: 
12156: @item n
12157: Nest; Single step through next word.
12158: 
12159: @item u
12160: Unnest; Stop debugging and execute rest of word. If we got to this word
12161: with nest, continue debugging with the calling word.
12162: 
12163: @item d
12164: Done; Stop debugging and execute rest.
12165: 
12166: @item s
12167: Stop; Abort immediately.
12168: 
12169: @end table
12170: 
12171: Debugging large application with this mechanism is very difficult, because
12172: you have to nest very deeply into the program before the interesting part
12173: begins. This takes a lot of time. 
12174: 
12175: To do it more directly put a @code{BREAK:} command into your source code.
12176: When program execution reaches @code{BREAK:} the single step debugger is
12177: invoked and you have all the features described above.
12178: 
12179: If you have more than one part to debug it is useful to know where the
12180: program has stopped at the moment. You can do this by the 
12181: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12182: string is typed out when the ``breakpoint'' is reached.
12183: 
12184: 
12185: doc-dbg
12186: doc-break:
12187: doc-break"
12188: 
12189: @c ------------------------------------------------------------
12190: @node C Interface, Assembler and Code Words, Programming Tools, Words
12191: @section C Interface
12192: @cindex C interface
12193: @cindex foreign language interface
12194: @cindex interface to C functions
12195: 
12196: Note that the C interface is not yet complete; callbacks are missing,
12197: as well as a way of declaring structs, unions, and their fields.
12198: 
12199: @menu
12200: * Calling C Functions::         
12201: * Declaring C Functions::       
12202: * Calling C function pointers::  
12203: * Defining library interfaces::  
12204: * Declaring OS-level libraries::  
12205: * Callbacks::                   
12206: * C interface internals::       
12207: * Low-Level C Interface Words::  
12208: @end menu
12209: 
12210: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
12211: @subsection Calling C functions
12212: @cindex C functions, calls to
12213: @cindex calling C functions
12214: 
12215: Once a C function is declared (see @pxref{Declaring C Functions}), you
12216: can call it as follows: You push the arguments on the stack(s), and
12217: then call the word for the C function.  The arguments have to be
12218: pushed in the same order as the arguments appear in the C
12219: documentation (i.e., the first argument is deepest on the stack).
12220: Integer and pointer arguments have to be pushed on the data stack,
12221: floating-point arguments on the FP stack; these arguments are consumed
12222: by the called C function.
12223: 
12224: On returning from the C function, the return value, if any, resides on
12225: the appropriate stack: an integer return value is pushed on the data
12226: stack, an FP return value on the FP stack, and a void return value
12227: results in not pushing anything.  Note that most C functions have a
12228: return value, even if that is often not used in C; in Forth, you have
12229: to @code{drop} this return value explicitly if you do not use it.
12230: 
12231: The C interface automatically converts between the C type and the
12232: Forth type as necessary, on a best-effort basis (in some cases, there
12233: may be some loss).
12234: 
12235: As an example, consider the POSIX function @code{lseek()}:
12236: 
12237: @example
12238: off_t lseek(int fd, off_t offset, int whence);
12239: @end example
12240: 
12241: This function takes three integer arguments, and returns an integer
12242: argument, so a Forth call for setting the current file offset to the
12243: start of the file could look like this:
12244: 
12245: @example
12246: fd @@ 0 SEEK_SET lseek -1 = if
12247:   ... \ error handling
12248: then
12249: @end example
12250: 
12251: You might be worried that an @code{off_t} does not fit into a cell, so
12252: you could not pass larger offsets to lseek, and might get only a part
12253: of the return values.  In that case, in your declaration of the
12254: function (@pxref{Declaring C Functions}) you should declare it to use
12255: double-cells for the off_t argument and return value, and maybe give
12256: the resulting Forth word a different name, like @code{dlseek}; the
12257: result could be called like this:
12258: 
12259: @example
12260: fd @@ 0. SEEK_SET dlseek -1. d= if
12261:   ... \ error handling
12262: then
12263: @end example
12264: 
12265: Passing and returning structs or unions is currently not supported by
12266: our interface@footnote{If you know the calling convention of your C
12267: compiler, you usually can call such functions in some way, but that
12268: way is usually not portable between platforms, and sometimes not even
12269: between C compilers.}.
12270: 
12271: Calling functions with a variable number of arguments (@emph{variadic}
12272: functions, e.g., @code{printf()}) is only supported by having you
12273: declare one function-calling word for each argument pattern, and
12274: calling the appropriate word for the desired pattern.
12275: 
12276: 
12277: 
12278: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
12279: @subsection Declaring C Functions
12280: @cindex C functions, declarations
12281: @cindex declaring C functions
12282: 
12283: Before you can call @code{lseek} or @code{dlseek}, you have to declare
12284: it.  The declaration consists of two parts: 
12285: 
12286: @table @b
12287: 
12288: @item The C part
12289: is the C declaration of the function, or more typically and portably,
12290: a C-style @code{#include} of a file that contains the declaration of
12291: the C function.
12292: 
12293: @item The Forth part
12294: declares the Forth types of the parameters and the Forth word name
12295: corresponding to the C function.
12296: 
12297: @end table
12298: 
12299: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12300: declarations are:
12301: 
12302: @example
12303: \c #define _FILE_OFFSET_BITS 64
12304: \c #include <sys/types.h>
12305: \c #include <unistd.h>
12306: c-function lseek lseek n n n -- n
12307: c-function dlseek lseek n d n -- d
12308: @end example
12309: 
12310: The C part of the declarations is prefixed by @code{\c}, and the rest
12311: of the line is ordinary C code.  You can use as many lines of C
12312: declarations as you like, and they are visible for all further
12313: function declarations.
12314: 
12315: The Forth part declares each interface word with @code{c-function},
12316: followed by the Forth name of the word, the C name of the called
12317: function, and the stack effect of the word.  The stack effect contains
12318: an arbitrary number of types of parameters, then @code{--}, and then
12319: exactly one type for the return value.  The possible types are:
12320: 
12321: @table @code
12322: 
12323: @item n
12324: single-cell integer
12325: 
12326: @item a
12327: address (single-cell)
12328: 
12329: @item d
12330: double-cell integer
12331: 
12332: @item r
12333: floating-point value
12334: 
12335: @item func
12336: C function pointer
12337: 
12338: @item void
12339: no value (used as return type for void functions)
12340: 
12341: @end table
12342: 
12343: @cindex variadic C functions
12344: 
12345: To deal with variadic C functions, you can declare one Forth word for
12346: every pattern you want to use, e.g.:
12347: 
12348: @example
12349: \c #include <stdio.h>
12350: c-function printf-nr printf a n r -- n
12351: c-function printf-rn printf a r n -- n
12352: @end example
12353: 
12354: Note that with C functions declared as variadic (or if you don't
12355: provide a prototype), the C interface has no C type to convert to, so
12356: no automatic conversion happens, which may lead to portability
12357: problems in some cases.  In such cases you can perform the conversion
12358: explicitly on the C level, e.g., as follows:
12359: 
12360: @example
12361: \c #define printfll(s,ll) printf(s,(long long)ll)
12362: c-function printfll printfll a n -- n
12363: @end example
12364: 
12365: Here, instead of calling @code{printf()} directly, we define a macro
12366: that casts (converts) the Forth single-cell integer into a
12367: C @code{long long} before calling @code{printf()}.
12368: 
12369: doc-\c
12370: doc-c-function
12371: doc-c-value
12372: doc-c-variable
12373: 
12374: In order to work, this C interface invokes GCC at run-time and uses
12375: dynamic linking.  If these features are not available, there are
12376: other, less convenient and less portable C interfaces in @file{lib.fs}
12377: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
12378: mostly incompatible with each other and with the documented C
12379: interface; you can find some examples for the @file{lib.fs} interface
12380: in @file{lib.fs}.
12381: 
12382: 
12383: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
12384: @subsection Calling C function pointers from Forth
12385: @cindex C function pointers, calling from Forth
12386: 
12387: If you come across a C function pointer (e.g., in some C-constructed
12388: structure) and want to call it from your Forth program, you can also
12389: use the features explained until now to achieve that, as follows:
12390: 
12391: Let us assume that there is a C function pointer type @code{func1}
12392: defined in some header file @file{func1.h}, and you know that these
12393: functions take one integer argument and return an integer result; and
12394: you want to call functions through such pointers.  Just define
12395: 
12396: @example
12397: \c #include <func1.h>
12398: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12399: c-function call-func1 call_func1 n func -- n
12400: @end example
12401: 
12402: and then you can call a function pointed to by, say @code{func1a} as
12403: follows:
12404: 
12405: @example
12406: -5 func1a call-func1 .
12407: @end example
12408: 
12409: In the C part, @code{call_func} is defined as a macro to avoid having
12410: to declare the exact parameter and return types, so the C compiler
12411: knows them from the declaration of @code{func1}.
12412: 
12413: The Forth word @code{call-func1} is similar to @code{execute}, except
12414: that it takes a C @code{func1} pointer instead of a Forth execution
12415: token, and it is specific to @code{func1} pointers.  For each type of
12416: function pointer you want to call from Forth, you have to define
12417: a separate calling word.
12418: 
12419: 
12420: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12421: @subsection Defining library interfaces
12422: @cindex giving a name to a library interface
12423: @cindex library interface names
12424: 
12425: You can give a name to a bunch of C function declarations (a library
12426: interface), as follows:
12427: 
12428: @example
12429: c-library lseek-lib
12430: \c #define _FILE_OFFSET_BITS 64
12431: ...
12432: end-c-library
12433: @end example
12434: 
12435: The effect of giving such a name to the interface is that the names of
12436: the generated files will contain that name, and when you use the
12437: interface a second time, it will use the existing files instead of
12438: generating and compiling them again, saving you time.  Note that even
12439: if you change the declarations, the old (stale) files will be used,
12440: probably leading to errors.  So, during development of the
12441: declarations we recommend not using @code{c-library}.  Normally these
12442: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12443: that directory you can get rid of stale files.
12444: 
12445: Note that you should use @code{c-library} before everything else
12446: having anything to do with that library, as it resets some setup
12447: stuff.  The idea is that the typical use is to put each
12448: @code{c-library}...@code{end-library} unit in its own file, and to be
12449: able to include these files in any order.
12450: 
12451: Note that the library name is not allocated in the dictionary and
12452: therefore does not shadow dictionary names.  It is used in the file
12453: system, so you have to use naming conventions appropriate for file
12454: systems.  Also, you must not call a function you declare after
12455: @code{c-library} before you perform @code{end-c-library}.
12456: 
12457: A major benefit of these named library interfaces is that, once they
12458: are generated, the tools used to generated them (in particular, the C
12459: compiler and libtool) are no longer needed, so the interface can be
12460: used even on machines that do not have the tools installed.
12461: 
12462: doc-c-library-name
12463: doc-c-library
12464: doc-end-c-library
12465: 
12466: 
12467: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12468: @subsection Declaring OS-level libraries
12469: @cindex Shared libraries in C interface
12470: @cindex Dynamically linked libraries in C interface
12471: @cindex Libraries in C interface
12472: 
12473: For calling some C functions, you need to link with a specific
12474: OS-level library that contains that function.  E.g., the @code{sin}
12475: function requires linking a special library by using the command line
12476: switch @code{-lm}.  In our C iterface you do the equivalent thing by
12477: calling @code{add-lib} as follows:
12478: 
12479: @example
12480: clear-libs
12481: s" m" add-lib
12482: \c #include <math.h>
12483: c-function sin sin r -- r
12484: @end example
12485: 
12486: First, you clear any libraries that may have been declared earlier
12487: (you don't need them for @code{sin}); then you add the @code{m}
12488: library (actually @code{libm.so} or somesuch) to the currently
12489: declared libraries; you can add as many as you need.  Finally you
12490: declare the function as shown above.  Typically you will use the same
12491: set of library declarations for many function declarations; you need
12492: to write only one set for that, right at the beginning.
12493: 
12494: Note that you must not call @code{clear-libs} inside
12495: @code{c-library...end-c-library}; however, @code{c-library} performs
12496: the function of @code{clear-libs}, so @code{clear-libs} is not
12497: necessary, and you usually want to put @code{add-lib} calls inside
12498: @code{c-library...end-c-library}.
12499: 
12500: doc-clear-libs
12501: doc-add-lib
12502: 
12503: 
12504: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
12505: @subsection Callbacks
12506: @cindex Callback functions written in Forth
12507: @cindex C function pointers to Forth words
12508: 
12509: Callbacks are not yet supported by the documented C interface.  You
12510: can use the undocumented @file{lib.fs} interface for callbacks.
12511: 
12512: In some cases you have to pass a function pointer to a C function,
12513: i.e., the library wants to call back to your application (and the
12514: pointed-to function is called a callback function).  You can pass the
12515: address of an existing C function (that you get with @code{lib-sym},
12516: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12517: function, you probably want to define the function as a Forth word.
12518: 
12519: @c I don't understand the existing callback interface from the example - anton
12520: 
12521: 
12522: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12523: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12524: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12525: @c > > C-Funktionsadresse auf dem TOS).
12526: @c >
12527: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12528: @c > gesehen habe, wozu das gut ist.
12529: @c 
12530: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
12531: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
12532: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
12533: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
12534: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
12535: @c demselben Prototyp.
12536: 
12537: 
12538: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
12539: @subsection How the C interface works
12540: 
12541: The documented C interface works by generating a C code out of the
12542: declarations.
12543: 
12544: In particular, for every Forth word declared with @code{c-function},
12545: it generates a wrapper function in C that takes the Forth data from
12546: the Forth stacks, and calls the target C function with these data as
12547: arguments.  The C compiler then performs an implicit conversion
12548: between the Forth type from the stack, and the C type for the
12549: parameter, which is given by the C function prototype.  After the C
12550: function returns, the return value is likewise implicitly converted to
12551: a Forth type and written back on the stack.
12552: 
12553: The @code{\c} lines are literally included in the C code (but without
12554: the @code{\c}), and provide the necessary declarations so that the C
12555: compiler knows the C types and has enough information to perform the
12556: conversion.
12557: 
12558: These wrapper functions are eventually compiled and dynamically linked
12559: into Gforth, and then they can be called.
12560: 
12561: The libraries added with @code{add-lib} are used in the compile
12562: command line to specify dependent libraries with @code{-l@var{lib}},
12563: causing these libraries to be dynamically linked when the wrapper
12564: function is linked.
12565: 
12566: 
12567: @node Low-Level C Interface Words,  , C interface internals, C Interface
12568: @subsection Low-Level C Interface Words
12569: 
12570: doc-open-lib
12571: doc-lib-sym
12572: doc-lib-error
12573: doc-call-c
12574: 
12575: @c -------------------------------------------------------------
12576: @node Assembler and Code Words, Threading Words, C Interface, Words
12577: @section Assembler and Code Words
12578: @cindex assembler
12579: @cindex code words
12580: 
12581: @menu
12582: * Assembler Definitions::       Definitions in assembly language
12583: * Common Assembler::            Assembler Syntax
12584: * Common Disassembler::         
12585: * 386 Assembler::               Deviations and special cases
12586: * AMD64 Assembler::             
12587: * Alpha Assembler::             Deviations and special cases
12588: * MIPS assembler::              Deviations and special cases
12589: * PowerPC assembler::           Deviations and special cases
12590: * ARM Assembler::               Deviations and special cases
12591: * Other assemblers::            How to write them
12592: @end menu
12593: 
12594: @node Assembler Definitions, Common Assembler, Assembler and Code Words, Assembler and Code Words
12595: @subsection Definitions in assembly language
12596: 
12597: Gforth provides ways to implement words in assembly language (using
12598: @code{abi-code}...@code{end-code}), and also ways to define defining
12599: words with arbitrary run-time behaviour (like @code{does>}), where
12600: (unlike @code{does>}) the behaviour is not defined in Forth, but in
12601: assembly language (with @code{;code}).
12602: 
12603: However, the machine-independent nature of Gforth poses a few
12604: problems: First of all, Gforth runs on several architectures, so it
12605: can provide no standard assembler. It does provide assemblers for
12606: several of the architectures it runs on, though.  Moreover, you can
12607: use a system-independent assembler in Gforth, or compile machine code
12608: directly with @code{,} and @code{c,}.
12609: 
12610: Another problem is that the virtual machine registers of Gforth (the
12611: stack pointers and the virtual machine instruction pointer) depend on
12612: the installation and engine.  Also, which registers are free to use
12613: also depend on the installation and engine.  So any code written to
12614: run in the context of the Gforth virtual machine is essentially
12615: limited to the installation and engine it was developed for (it may
12616: run elsewhere, but you cannot rely on that).
12617: 
12618: Fortunately, you can define @code{abi-code} words in Gforth that are
12619: portable to any Gforth running on a platform with the same calling
12620: convention (ABI); typically this means portability to the same
12621: architecture/OS combination, sometimes crossing OS boundaries).
12622: 
12623: doc-assembler
12624: doc-init-asm
12625: doc-abi-code
12626: doc-end-code
12627: doc-code
12628: doc-;code
12629: doc-flush-icache
12630: 
12631: 
12632: If @code{flush-icache} does not work correctly, @code{abi-code} words
12633: etc. will not work (reliably), either.
12634: 
12635: The typical usage of these words can be shown most easily by analogy
12636: to the equivalent high-level defining words:
12637: 
12638: @example
12639: : foo                              abi-code foo
12640:    <high-level Forth words>              <assembler>
12641: ;                                  end-code
12642:                                 
12643: : bar                              : bar
12644:    <high-level Forth words>           <high-level Forth words>
12645:    CREATE                             CREATE
12646:       <high-level Forth words>           <high-level Forth words>
12647:    DOES>                              ;code
12648:       <high-level Forth words>           <assembler>
12649: ;                                  end-code
12650: @end example
12651: 
12652: For using @code{abi-code}, take a look at the ABI documentation of
12653: your platform to see how the parameters are passed (so you know where
12654: you get the stack pointers) and how the return value is passed (so you
12655: know where the data stack pointer is returned).  The ABI documentation
12656: also tells you which registers are saved by the caller (caller-saved),
12657: so you are free to destroy them in your code, and which registers have
12658: to be preserved by the called word (callee-saved), so you have to save
12659: them before using them, and restore them afterwards.  For some
12660: architectures and OSs we give short summaries of the parts of the
12661: calling convention in the appropriate sections.  More
12662: reverse-engineering oriented people can also find out about the
12663: passing and returning of the stack pointers through @code{see
12664: abi-call}.
12665: 
12666: Most ABIs pass the parameters through registers, but some (in
12667: particular the most common 386 (aka IA-32) calling conventions) pass
12668: them on the architectural stack.  The common ABIs all pass the return
12669: value in a register.
12670: 
12671: Other things you need to know for using @code{abi-code} is that both
12672: the data and the FP stack grow downwards (towards lower addresses) in
12673: Gforth, with @code{1 cells} size per cell, and @code{1 floats} size
12674: per FP value.
12675: 
12676: Here's an example of using @code{abi-code} on the 386 architecture:
12677: 
12678: @example
12679: abi-code my+ ( n1 n2 -- n )
12680: 4 sp d) ax mov \ sp into return reg
12681: ax )    cx mov \ tos
12682: 4 #     ax add \ update sp (pop)
12683: cx    ax ) add \ sec = sec+tos
12684: ret            \ return from my+
12685: end-code
12686: @end example
12687: 
12688: An AMD64 variant of this example can be found in @ref{AMD64 Assembler}.
12689: 
12690: Here's a 386 example that deals with FP values:
12691: 
12692: @example
12693: abi-code my-f+ ( r1 r2 -- r )
12694: 8 sp d) cx mov  \ load address of fp
12695: cx )    dx mov  \ load fp
12696: .fl dx )   fld  \ r2
12697: 8 #     dx add  \ update fp
12698: .fl dx )   fadd \ r1+r2
12699: .fl dx )   fstp \ store r
12700: dx    cx ) mov  \ store new fp
12701: 4 sp d) ax mov  \ sp into return reg
12702: ret             \ return from my-f+
12703: end-code
12704: @end example
12705: 
12706: 
12707: @node Common Assembler, Common Disassembler, Assembler Definitions, Assembler and Code Words
12708: @subsection Common Assembler
12709: 
12710: The assemblers in Gforth generally use a postfix syntax, i.e., the
12711: instruction name follows the operands.
12712: 
12713: The operands are passed in the usual order (the same that is used in the
12714: manual of the architecture).  Since they all are Forth words, they have
12715: to be separated by spaces; you can also use Forth words to compute the
12716: operands.
12717: 
12718: The instruction names usually end with a @code{,}.  This makes it easier
12719: to visually separate instructions if you put several of them on one
12720: line; it also avoids shadowing other Forth words (e.g., @code{and}).
12721: 
12722: Registers are usually specified by number; e.g., (decimal) @code{11}
12723: specifies registers R11 and F11 on the Alpha architecture (which one,
12724: depends on the instruction).  The usual names are also available, e.g.,
12725: @code{s2} for R11 on Alpha.
12726: 
12727: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12728: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12729: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12730: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
12731: conditions are specified in a way specific to each assembler.
12732: 
12733: The rest of this section is of interest mainly for those who want to
12734: define @code{code} words (instead of the more portable @code{abi-code}
12735: words).
12736: 
12737: Note that the register assignments of the Gforth engine can change
12738: between Gforth versions, or even between different compilations of the
12739: same Gforth version (e.g., if you use a different GCC version).  If
12740: you are using @code{CODE} instead of @code{ABI-CODE}, and you want to
12741: refer to Gforth's registers (e.g., the stack pointer or TOS), I
12742: recommend defining your own words for refering to these registers, and
12743: using them later on; then you can adapt to a changed register
12744: assignment.
12745: 
12746: The most common use of these registers is to end a @code{code}
12747: definition with a dispatch to the next word (the @code{next} routine).
12748: A portable way to do this is to jump to @code{' noop >code-address}
12749: (of course, this is less efficient than integrating the @code{next}
12750: code and scheduling it well).  When using @code{ABI-CODE}, you can
12751: just assemble a normal subroutine return (but make sure you return the
12752: data stack pointer).
12753: 
12754: Another difference between Gforth versions is that the top of stack is
12755: kept in memory in @code{gforth} and, on most platforms, in a register
12756: in @code{gforth-fast}.  For @code{ABI-CODE} definitions, any stack
12757: caching registers are guaranteed to be flushed to the stack, allowing
12758: you to reliably access the top of stack in memory.
12759: 
12760: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12761: @subsection Common Disassembler
12762: @cindex disassembler, general
12763: @cindex gdb disassembler
12764: 
12765: You can disassemble a @code{code} word with @code{see}
12766: (@pxref{Debugging}).  You can disassemble a section of memory with
12767: 
12768: doc-discode
12769: 
12770: There are two kinds of disassembler for Gforth: The Forth disassembler
12771: (available on some CPUs) and the gdb disassembler (available on
12772: platforms with @command{gdb} and @command{mktemp}).  If both are
12773: available, the Forth disassembler is used by default.  If you prefer
12774: the gdb disassembler, say
12775: 
12776: @example
12777: ' disasm-gdb is discode
12778: @end example
12779: 
12780: If neither is available, @code{discode} performs @code{dump}.
12781: 
12782: The Forth disassembler generally produces output that can be fed into the
12783: assembler (i.e., same syntax, etc.).  It also includes additional
12784: information in comments.  In particular, the address of the instruction
12785: is given in a comment before the instruction.
12786: 
12787: The gdb disassembler produces output in the same format as the gdb
12788: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12789: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12790: the 386 and AMD64 architectures).
12791: 
12792: @code{See} may display more or less than the actual code of the word,
12793: because the recognition of the end of the code is unreliable.  You can
12794: use @code{discode} if it did not display enough.  It may display more, if
12795: the code word is not immediately followed by a named word.  If you have
12796: something else there, you can follow the word with @code{align latest ,}
12797: to ensure that the end is recognized.
12798: 
12799: @node 386 Assembler, AMD64 Assembler, Common Disassembler, Assembler and Code Words
12800: @subsection 386 Assembler
12801: 
12802: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12803: available under GPL, and originally part of bigFORTH.
12804: 
12805: The 386 disassembler included in Gforth was written by Andrew McKewan
12806: and is in the public domain.
12807: 
12808: The disassembler displays code in an Intel-like prefix syntax.
12809: 
12810: The assembler uses a postfix syntax with AT&T-style parameter order
12811: (i.e., destination last).
12812: 
12813: The assembler includes all instruction of the Athlon, i.e. 486 core
12814: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12815: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12816: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12817: 
12818: There are several prefixes to switch between different operation sizes,
12819: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12820: double-word accesses. Addressing modes can be switched with @code{.wa}
12821: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12822: need a prefix for byte register names (@code{AL} et al).
12823: 
12824: For floating point operations, the prefixes are @code{.fs} (IEEE
12825: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12826: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).  The
12827: default is @code{.fx}, so you need to specify @code{.fl} explicitly
12828: when dealing with Gforth FP values.
12829: 
12830: The MMX opcodes don't have size prefixes, they are spelled out like in
12831: the Intel assembler. Instead of move from and to memory, there are
12832: PLDQ/PLDD and PSTQ/PSTD.
12833: 
12834: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12835: ax.  Immediate values are indicated by postfixing them with @code{#},
12836: e.g., @code{3 #}.  Here are some examples of addressing modes in various
12837: syntaxes:
12838: 
12839: @example
12840: Gforth          Intel (NASM)   AT&T (gas)      Name
12841: .w ax           ax             %ax             register (16 bit)
12842: ax              eax            %eax            register (32 bit)
12843: 3 #             offset 3       $3              immediate
12844: 1000 #)         byte ptr 1000  1000            displacement
12845: bx )            [ebx]          (%ebx)          base
12846: 100 di d)       100[edi]       100(%edi)       base+displacement
12847: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
12848: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
12849: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
12850: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12851: @end example
12852: 
12853: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12854: @code{DI)} to enforce 32-bit displacement fields (useful for
12855: later patching).
12856: 
12857: Some example of instructions are:
12858: 
12859: @example
12860: ax bx mov             \ move ebx,eax
12861: 3 # ax mov            \ mov eax,3
12862: 100 di d) ax mov      \ mov eax,100[edi]
12863: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
12864: .w ax bx mov          \ mov bx,ax
12865: @end example
12866: 
12867: The following forms are supported for binary instructions:
12868: 
12869: @example
12870: <reg> <reg> <inst>
12871: <n> # <reg> <inst>
12872: <mem> <reg> <inst>
12873: <reg> <mem> <inst>
12874: <n> # <mem> <inst>
12875: @end example
12876: 
12877: The shift/rotate syntax is:
12878: 
12879: @example
12880: <reg/mem> 1 # shl \ shortens to shift without immediate
12881: <reg/mem> 4 # shl
12882: <reg/mem> cl shl
12883: @end example
12884: 
12885: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12886: the byte version.
12887: 
12888: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12889: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12890: pc < >= <= >}. (Note that most of these words shadow some Forth words
12891: when @code{assembler} is in front of @code{forth} in the search path,
12892: e.g., in @code{code} words).  Currently the control structure words use
12893: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12894: to shuffle them (you can also use @code{swap} etc.).
12895: 
12896: Based on the Intel ABI (used in Linux), @code{abi-code} words can find
12897: the data stack pointer at @code{4 sp d)}, and the address of the FP
12898: stack pointer at @code{8 sp d)}; the data stack pointer is returned in
12899: @code{ax}; @code{Ax}, @code{cx}, and @code{dx} are caller-saved, so
12900: you do not need to preserve their values inside the word.  You can
12901: return from the word with @code{ret}, the parameters are cleaned up by
12902: the caller.
12903: 
12904: For examples of 386 @code{abi-code} words, see @ref{Assembler Definitions}.
12905: 
12906: 
12907: @node AMD64 Assembler, Alpha Assembler, 386 Assembler, Assembler and Code Words
12908: @subsection AMD64 (x86_64) Assembler
12909: 
12910: The AMD64 assembler is a slightly modified version of the 386
12911: assembler, and as such shares most of the syntax.  Two new prefixes,
12912: @code{.q} and @code{.qa}, are provided to select 64-bit operand and
12913: address sizes respectively.  64-bit sizes are the default, so normally
12914: you only have to use the other prefixes.  Also there are additional
12915: register operands @code{R8}-@code{R15}.
12916: 
12917: The registers lack the 'e' or 'r' prefix; even in 64 bit mode,
12918: @code{rax} is called @code{ax}.  Additional register operands are
12919: available to refer to the lowest-significant byte of all registers:
12920: @code{R8L}-@code{R15L}, @code{SPL}, @code{BPL}, @code{SIL},
12921: @code{DIL}.
12922: 
12923: The Linux-AMD64 calling convention is to pass the first 6 integer
12924: parameters in rdi, rsi, rdx, rcx, r8 and r9 and to return the result
12925: in rax and rdx; to pass the first 8 FP parameters in xmm0--xmm7 and to
12926: return FP results in xmm0--xmm1.  So @code{abi-code} words get the
12927: data stack pointer in @code{di} and the address of the FP stack
12928: pointer in @code{si}, and return the data stack pointer in @code{ax}.
12929: The other caller-saved registers are: r10, r11, xmm8-xmm15.  This
12930: calling convention reportedly is also used in other non-Microsoft OSs.
12931: @c source: http://en.wikipedia.org/wiki/X86_calling_conventions#AMD64_ABI_convention
12932: 
12933: @c source: http://msdn.microsoft.com/en-us/library/9b372w95(v=VS.90).aspx
12934: Windows x64 passes the first four integer parameters in rcx, rdx, r8
12935: and r9 and return the integer result in rax.  The other caller-saved
12936: registers are r10 and r11.
12937: 
12938: Here is an example of an AMD64 @code{abi-code} word:
12939: 
12940: @example
12941: abi-code my+  ( n1 n2 -- n3 )
12942: \ SP passed in di, returned in ax,  address of FP passed in si
12943: 8 di d) ax lea        \ compute new sp in result reg
12944: di )    dx mov        \ get old tos
12945: dx    ax ) add        \ add to new tos
12946: ret
12947: end-code
12948: @end example
12949: 
12950: Here's a AMD64 example that deals with FP values:
12951: 
12952: @example
12953: abi-code my-f+  ( r1 r2 -- r )
12954: \ SP passed in di, returned in ax,  address of FP passed in si
12955: si )       dx mov         \ load fp
12956: 8 dx d)  xmm0 movsd       \ r2
12957: dx )     xmm0 addsd       \ r1+r2
12958: xmm0  8 dx d) movsd       \ store r
12959: 8 #      si ) add         \ update fp
12960: di         ax mov         \ sp into return reg
12961: ret
12962: end-code
12963: @end example
12964: 
12965: @node Alpha Assembler, MIPS assembler, AMD64 Assembler, Assembler and Code Words
12966: @subsection Alpha Assembler
12967: 
12968: The Alpha assembler and disassembler were originally written by Bernd
12969: Thallner.
12970: 
12971: The register names @code{a0}--@code{a5} are not available to avoid
12972: shadowing hex numbers.
12973: 
12974: Immediate forms of arithmetic instructions are distinguished by a
12975: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12976: does not count as arithmetic instruction).
12977: 
12978: You have to specify all operands to an instruction, even those that
12979: other assemblers consider optional, e.g., the destination register for
12980: @code{br,}, or the destination register and hint for @code{jmp,}.
12981: 
12982: You can specify conditions for @code{if,} by removing the first @code{b}
12983: and the trailing @code{,} from a branch with a corresponding name; e.g.,
12984: 
12985: @example
12986: 11 fgt if, \ if F11>0e
12987:   ...
12988: endif,
12989: @end example
12990: 
12991: @code{fbgt,} gives @code{fgt}.  
12992: 
12993: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
12994: @subsection MIPS assembler
12995: 
12996: The MIPS assembler was originally written by Christian Pirker.
12997: 
12998: Currently the assembler and disassembler covers most of the MIPS32
12999: architecture and doesn't support FP instructions.
13000: 
13001: The register names @code{$a0}--@code{$a3} are not available to avoid
13002: shadowing hex numbers.  Use register numbers @code{$4}--@code{$7}
13003: instead.
13004: 
13005: Nothing distinguishes registers from immediate values.  Use explicit
13006: opcode names with the @code{i} suffix for instructions with immediate
13007: argument.  E.g. @code{addiu,} in place of @code{addu,}.
13008: 
13009: Where the architecture manual specifies several formats for the
13010: instruction (e.g., for @code{jalr,}),use the one with more arguments
13011: (i.e. two for @code{jalr,}).  When in doubt, see
13012: @code{arch/mips/testasm.fs} for an example of correct use.
13013: 
13014: Branches and jumps in the MIPS architecture have a delay slot.  You
13015: have to fill it manually (the simplest way is to use @code{nop,}), the
13016: assembler does not do it for you (unlike @command{as}).  Even
13017: @code{if,}, @code{ahead,}, @code{until,}, @code{again,},
13018: @code{while,}, @code{else,} and @code{repeat,} need a delay slot.
13019: Since @code{begin,} and @code{then,} just specify branch targets, they
13020: are not affected.  For branches the argument specifying the target is
13021: a relative address.  Add the address of the delay slot to get the
13022: absolute address.
13023: 
13024: Note that you must not put branches nor jumps (nor control-flow
13025: instructions) into the delay slot.  Also it is a bad idea to put
13026: pseudo-ops such as @code{li,} into a delay slot, as these may expand
13027: to several instructions.  The MIPS I architecture also had load delay
13028: slots, and newer MIPSes still have restrictions on using @code{mfhi,}
13029: and @code{mflo,}.  Be careful to satisfy these restrictions, the
13030: assembler does not do it for you.
13031: 
13032: Some example of instructions are:
13033: 
13034: @example
13035: $ra  12 $sp  sw,         \ sw    ra,12(sp)
13036: $4    8 $s0  lw,         \ lw    a0,8(s0)
13037: $v0  $0  lui,            \ lui   v0,0x0
13038: $s0  $s4  $12  addiu,    \ addiu s0,s4,0x12
13039: $s0  $s4  $4  addu,      \ addu  s0,s4,$a0
13040: $ra  $t9  jalr,          \ jalr  t9
13041: @end example
13042: 
13043: You can specify the conditions for @code{if,} etc. by taking a
13044: conditional branch and leaving away the @code{b} at the start and the
13045: @code{,} at the end.  E.g.,
13046: 
13047: @example
13048: 4 5 eq if,
13049:   ... \ do something if $4 equals $5
13050: then,
13051: @end example
13052: 
13053: The calling conventions for 32-bit MIPS machines is to pass the first
13054: 4 arguments in registers @code{$4}..@code{$7}, and to use
13055: @code{$v0}-@code{$v1} for return values.  In addition to these
13056: registers, it is ok to clobber registers @code{$t0}-@code{$t8} without
13057: saving and restoring them.
13058: 
13059: If you use @code{jalr,} to call into dynamic library routines, you
13060: must first load the called function's address into @code{$t9}, which
13061: is used by position-indirect code to do relative memory accesses.
13062: 
13063: Here is an example of a MIPS32 @code{abi-code} word:
13064: 
13065: @example
13066: abi-code my+  ( n1 n2 -- n3 )
13067:   \ SP passed in $4, returned in $v0
13068:   $t0  4 $4  lw,         \ load n1, n2 from stack
13069:   $t1  0 $4  lw,    
13070:   $t0  $t0  $t1  addu,   \ add n1+n2, result in $t0
13071:   $t0  4 $4  sw,         \ store result (overwriting n1)
13072:   $ra  jr,               \ return to caller
13073:   $v0  $4  4  addiu,     \ (delay slot) return uptated SP in $v0
13074: end-code
13075: @end example
13076: 
13077: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
13078: @subsection PowerPC assembler
13079: 
13080: The PowerPC assembler and disassembler were contributed by Michal
13081: Revucky.
13082: 
13083: This assembler does not follow the convention of ending mnemonic names
13084: with a ``,'', so some mnemonic names shadow regular Forth words (in
13085: particular: @code{and or xor fabs}); so if you want to use the Forth
13086: words, you have to make them visible first, e.g., with @code{also
13087: forth}.
13088: 
13089: Registers are referred to by their number, e.g., @code{9} means the
13090: integer register 9 or the FP register 9 (depending on the
13091: instruction).
13092: 
13093: Because there is no way to distinguish registers from immediate values,
13094: you have to explicitly use the immediate forms of instructions, i.e.,
13095: @code{addi,}, not just @code{add,}.
13096: 
13097: The assembler and disassembler usually support the most general form
13098: of an instruction, but usually not the shorter forms (especially for
13099: branches).
13100: 
13101: 
13102: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
13103: @subsection ARM Assembler
13104: 
13105: The ARM assembler includes all instruction of ARM architecture version
13106: 4, and the BLX instruction from architecture 5.  It does not (yet)
13107: have support for Thumb instructions.  It also lacks support for any
13108: co-processors.
13109: 
13110: The assembler uses a postfix syntax with the same operand order as
13111: used in the ARM Architecture Reference Manual.  Mnemonics are suffixed
13112: by a comma.
13113: 
13114: Registers are specified by their names @code{r0} through @code{r15},
13115: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
13116: @code{fp} provided for convenience.  Note that @code{ip} refers to
13117: the``intra procedure call scratch register'' (@code{r12}) and does not
13118: refer to an instruction pointer.  @code{sp} refers to the ARM ABI
13119: stack pointer (@code{r13}) and not the Forth stack pointer.
13120: 
13121: Condition codes can be specified anywhere in the instruction, but will
13122: be most readable if specified just in front of the mnemonic.  The 'S'
13123: flag is not a separate word, but encoded into instruction mnemonics,
13124: ie. just use @code{adds,} instead of @code{add,} if you want the
13125: status register to be updated.
13126: 
13127: The following table lists the syntax of operands for general
13128: instructions:
13129: 
13130: @example
13131: Gforth          normal assembler      description
13132: 123 #           #123                  immediate
13133: r12             r12                   register
13134: r12 4 #LSL      r12, LSL #4           shift left by immediate
13135: r12 r1 #LSL     r12, LSL r1           shift left by register
13136: r12 4 #LSR      r12, LSR #4           shift right by immediate
13137: r12 r1 #LSR     r12, LSR r1           shift right by register
13138: r12 4 #ASR      r12, ASR #4           arithmetic shift right
13139: r12 r1 #ASR     r12, ASR r1           ... by register
13140: r12 4 #ROR      r12, ROR #4           rotate right by immediate
13141: r12 r1 #ROR     r12, ROR r1           ... by register
13142: r12 RRX         r12, RRX              rotate right with extend by 1
13143: @end example
13144: 
13145: Memory operand syntax is listed in this table:
13146: 
13147: @example
13148: Gforth            normal assembler      description
13149: r4 ]              [r4]                  register
13150: r4 4 #]           [r4, #+4]             register with immediate offset
13151: r4 -4 #]          [r4, #-4]             with negative offset
13152: r4 r1 +]          [r4, +r1]             register with register offset
13153: r4 r1 -]          [r4, -r1]             with negated register offset
13154: r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
13155: r4 4 #]!          [r4, #+4]!            immediate preincrement
13156: r4 r1 +]!         [r4, +r1]!            register preincrement
13157: r4 r1 -]!         [r4, +r1]!            register predecrement
13158: r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
13159: r4 -4 ]#          [r4], #-4             immediate postdecrement
13160: r4 r1 ]+          [r4], r1              register postincrement
13161: r4 r1 ]-          [r4], -r1             register postdecrement
13162: r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
13163: ' xyz >body [#]   xyz                   PC-relative addressing
13164: @end example
13165: 
13166: Register lists for load/store multiple instructions are started and
13167: terminated by using the words @code{@{} and @code{@}} respectively.
13168: Between braces, register names can be listed one by one or register
13169: ranges can be formed by using the postfix operator @code{r-r}.  The
13170: @code{^} flag is not encoded in the register list operand, but instead
13171: directly encoded into the instruction mnemonic, ie. use @code{^ldm,}
13172: and @code{^stm,}.
13173: 
13174: Addressing modes for load/store multiple are not encoded as
13175: instruction suffixes, but instead specified like an addressing mode,
13176: Use one of @code{DA}, @code{IA}, @code{DB}, @code{IB}, @code{DA!},
13177: @code{IA!}, @code{DB!} or @code{IB!}.
13178: 
13179: The following table gives some examples:
13180: 
13181: @example
13182: Gforth                           normal assembler
13183: r4 ia  @{ r0 r7 r8 @}  stm,        stmia    r4, @{r0,r7,r8@}
13184: r4 db!  @{ r0 r7 r8 @}  ldm,       ldmdb    r4!, @{r0,r7,r8@}
13185: sp ia!  @{ r0 r15 r-r @}  ^ldm,    ldmfd    sp!, @{r0-r15@}^
13186: @end example
13187: 
13188: Control structure words typical for Forth assemblers are available:
13189: @code{if,} @code{ahead,} @code{then,} @code{else,} @code{begin,}
13190: @code{until,} @code{again,} @code{while,} @code{repeat,}
13191: @code{repeat-until,}.  Conditions are specified in front of these words:
13192: 
13193: @example
13194: r1 r2 cmp,    \ compare r1 and r2
13195: eq if,        \ equal?
13196:    ...          \ code executed if r1 == r2
13197: then,
13198: @end example
13199: 
13200: Example of a definition using the ARM assembler:
13201: 
13202: @example
13203: abi-code my+ ( n1 n2 --  n3 )
13204:    \ arm abi: r0=SP, r1=&FP, r2,r3,r12 saved by caller
13205:    r0 IA!  @{ r2 r3 @}  ldm,     \ pop r2 = n2, r3 = n1
13206:    r3  r2  r3         add,     \ r3 = n1+n1
13207:    r3  r0 -4 #]!      str,     \ push r3
13208:    pc  lr             mov,     \ return to caller, new SP in r0
13209: end-code
13210: @end example
13211: 
13212: @node Other assemblers,  , ARM Assembler, Assembler and Code Words
13213: @subsection Other assemblers
13214: 
13215: If you want to contribute another assembler/disassembler, please contact
13216: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
13217: an assembler already.  If you are writing them from scratch, please use
13218: a similar syntax style as the one we use (i.e., postfix, commas at the
13219: end of the instruction names, @pxref{Common Assembler}); make the output
13220: of the disassembler be valid input for the assembler, and keep the style
13221: similar to the style we used.
13222: 
13223: Hints on implementation: The most important part is to have a good test
13224: suite that contains all instructions.  Once you have that, the rest is
13225: easy.  For actual coding you can take a look at
13226: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
13227: the assembler and disassembler, avoiding redundancy and some potential
13228: bugs.  You can also look at that file (and @pxref{Advanced does> usage
13229: example}) to get ideas how to factor a disassembler.
13230: 
13231: Start with the disassembler, because it's easier to reuse data from the
13232: disassembler for the assembler than the other way round.
13233: 
13234: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13235: how simple it can be.
13236: 
13237: 
13238: 
13239: 
13240: @c -------------------------------------------------------------
13241: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13242: @section Threading Words
13243: @cindex threading words
13244: 
13245: @cindex code address
13246: These words provide access to code addresses and other threading stuff
13247: in Gforth (and, possibly, other interpretive Forths). It more or less
13248: abstracts away the differences between direct and indirect threading
13249: (and, for direct threading, the machine dependences). However, at
13250: present this wordset is still incomplete. It is also pretty low-level;
13251: some day it will hopefully be made unnecessary by an internals wordset
13252: that abstracts implementation details away completely.
13253: 
13254: The terminology used here stems from indirect threaded Forth systems; in
13255: such a system, the XT of a word is represented by the CFA (code field
13256: address) of a word; the CFA points to a cell that contains the code
13257: address.  The code address is the address of some machine code that
13258: performs the run-time action of invoking the word (e.g., the
13259: @code{dovar:} routine pushes the address of the body of the word (a
13260: variable) on the stack
13261: ).
13262: 
13263: @cindex code address
13264: @cindex code field address
13265: In an indirect threaded Forth, you can get the code address of @i{name}
13266: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13267: >code-address}, independent of the threading method.
13268: 
13269: doc-threading-method
13270: doc->code-address
13271: doc-code-address!
13272: 
13273: @cindex @code{does>}-handler
13274: @cindex @code{does>}-code
13275: For a word defined with @code{DOES>}, the code address usually points to
13276: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13277: routine (in Gforth on some platforms, it can also point to the dodoes
13278: routine itself).  What you are typically interested in, though, is
13279: whether a word is a @code{DOES>}-defined word, and what Forth code it
13280: executes; @code{>does-code} tells you that.
13281: 
13282: doc->does-code
13283: 
13284: To create a @code{DOES>}-defined word with the following basic words,
13285: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13286: @code{/does-handler} aus behind you have to place your executable Forth
13287: code.  Finally you have to create a word and modify its behaviour with
13288: @code{does-handler!}.
13289: 
13290: doc-does-code!
13291: doc-does-handler!
13292: doc-/does-handler
13293: 
13294: The code addresses produced by various defining words are produced by
13295: the following words:
13296: 
13297: doc-docol:
13298: doc-docon:
13299: doc-dovar:
13300: doc-douser:
13301: doc-dodefer:
13302: doc-dofield:
13303: 
13304: @cindex definer
13305: The following two words generalize @code{>code-address},
13306: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13307: 
13308: doc->definer
13309: doc-definer!
13310: 
13311: @c -------------------------------------------------------------
13312: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
13313: @section Passing Commands to the Operating System
13314: @cindex operating system - passing commands
13315: @cindex shell commands
13316: 
13317: Gforth allows you to pass an arbitrary string to the host operating
13318: system shell (if such a thing exists) for execution.
13319: 
13320: doc-sh
13321: doc-system
13322: doc-$?
13323: doc-getenv
13324: 
13325: @c -------------------------------------------------------------
13326: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13327: @section Keeping track of Time
13328: @cindex time-related words
13329: 
13330: doc-ms
13331: doc-time&date
13332: doc-utime
13333: doc-cputime
13334: 
13335: 
13336: @c -------------------------------------------------------------
13337: @node Miscellaneous Words,  , Keeping track of Time, Words
13338: @section Miscellaneous Words
13339: @cindex miscellaneous words
13340: 
13341: @comment TODO find homes for these
13342: 
13343: These section lists the ANS Forth words that are not documented
13344: elsewhere in this manual. Ultimately, they all need proper homes.
13345: 
13346: doc-quit
13347: 
13348: The following ANS Forth words are not currently supported by Gforth 
13349: (@pxref{ANS conformance}):
13350: 
13351: @code{EDITOR} 
13352: @code{EMIT?} 
13353: @code{FORGET} 
13354: 
13355: @c ******************************************************************
13356: @node Error messages, Tools, Words, Top
13357: @chapter Error messages
13358: @cindex error messages
13359: @cindex backtrace
13360: 
13361: A typical Gforth error message looks like this:
13362: 
13363: @example
13364: in file included from \evaluated string/:-1
13365: in file included from ./yyy.fs:1
13366: ./xxx.fs:4: Invalid memory address
13367: >>>bar<<<
13368: Backtrace:
13369: $400E664C @@
13370: $400E6664 foo
13371: @end example
13372: 
13373: The message identifying the error is @code{Invalid memory address}.  The
13374: error happened when text-interpreting line 4 of the file
13375: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13376: word on the line where the error happened, is pointed out (with
13377: @code{>>>} and @code{<<<}).
13378: 
13379: The file containing the error was included in line 1 of @file{./yyy.fs},
13380: and @file{yyy.fs} was included from a non-file (in this case, by giving
13381: @file{yyy.fs} as command-line parameter to Gforth).
13382: 
13383: At the end of the error message you find a return stack dump that can be
13384: interpreted as a backtrace (possibly empty). On top you find the top of
13385: the return stack when the @code{throw} happened, and at the bottom you
13386: find the return stack entry just above the return stack of the topmost
13387: text interpreter.
13388: 
13389: To the right of most return stack entries you see a guess for the word
13390: that pushed that return stack entry as its return address. This gives a
13391: backtrace. In our case we see that @code{bar} called @code{foo}, and
13392: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13393: address} exception).
13394: 
13395: Note that the backtrace is not perfect: We don't know which return stack
13396: entries are return addresses (so we may get false positives); and in
13397: some cases (e.g., for @code{abort"}) we cannot determine from the return
13398: address the word that pushed the return address, so for some return
13399: addresses you see no names in the return stack dump.
13400: 
13401: @cindex @code{catch} and backtraces
13402: The return stack dump represents the return stack at the time when a
13403: specific @code{throw} was executed.  In programs that make use of
13404: @code{catch}, it is not necessarily clear which @code{throw} should be
13405: used for the return stack dump (e.g., consider one @code{throw} that
13406: indicates an error, which is caught, and during recovery another error
13407: happens; which @code{throw} should be used for the stack dump?).
13408: Gforth presents the return stack dump for the first @code{throw} after
13409: the last executed (not returned-to) @code{catch} or @code{nothrow};
13410: this works well in the usual case. To get the right backtrace, you
13411: usually want to insert @code{nothrow} or @code{['] false catch drop}
13412: after a @code{catch} if the error is not rethrown.
13413: 
13414: @cindex @code{gforth-fast} and backtraces
13415: @cindex @code{gforth-fast}, difference from @code{gforth}
13416: @cindex backtraces with @code{gforth-fast}
13417: @cindex return stack dump with @code{gforth-fast}
13418: @code{Gforth} is able to do a return stack dump for throws generated
13419: from primitives (e.g., invalid memory address, stack empty etc.);
13420: @code{gforth-fast} is only able to do a return stack dump from a
13421: directly called @code{throw} (including @code{abort} etc.).  Given an
13422: exception caused by a primitive in @code{gforth-fast}, you will
13423: typically see no return stack dump at all; however, if the exception is
13424: caught by @code{catch} (e.g., for restoring some state), and then
13425: @code{throw}n again, the return stack dump will be for the first such
13426: @code{throw}.
13427: 
13428: @c ******************************************************************
13429: @node Tools, ANS conformance, Error messages, Top
13430: @chapter Tools
13431: 
13432: @menu
13433: * ANS Report::                  Report the words used, sorted by wordset.
13434: * Stack depth changes::         Where does this stack item come from?
13435: @end menu
13436: 
13437: See also @ref{Emacs and Gforth}.
13438: 
13439: @node ANS Report, Stack depth changes, Tools, Tools
13440: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13441: @cindex @file{ans-report.fs}
13442: @cindex report the words used in your program
13443: @cindex words used in your program
13444: 
13445: If you want to label a Forth program as ANS Forth Program, you must
13446: document which wordsets the program uses; for extension wordsets, it is
13447: helpful to list the words the program requires from these wordsets
13448: (because Forth systems are allowed to provide only some words of them).
13449: 
13450: The @file{ans-report.fs} tool makes it easy for you to determine which
13451: words from which wordset and which non-ANS words your application
13452: uses. You simply have to include @file{ans-report.fs} before loading the
13453: program you want to check. After loading your program, you can get the
13454: report with @code{print-ans-report}. A typical use is to run this as
13455: batch job like this:
13456: @example
13457: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13458: @end example
13459: 
13460: The output looks like this (for @file{compat/control.fs}):
13461: @example
13462: The program uses the following words
13463: from CORE :
13464: : POSTPONE THEN ; immediate ?dup IF 0= 
13465: from BLOCK-EXT :
13466: \ 
13467: from FILE :
13468: ( 
13469: @end example
13470: 
13471: @subsection Caveats
13472: 
13473: Note that @file{ans-report.fs} just checks which words are used, not whether
13474: they are used in an ANS Forth conforming way!
13475: 
13476: Some words are defined in several wordsets in the
13477: standard. @file{ans-report.fs} reports them for only one of the
13478: wordsets, and not necessarily the one you expect. It depends on usage
13479: which wordset is the right one to specify. E.g., if you only use the
13480: compilation semantics of @code{S"}, it is a Core word; if you also use
13481: its interpretation semantics, it is a File word.
13482: 
13483: 
13484: @node Stack depth changes,  , ANS Report, Tools
13485: @section Stack depth changes during interpretation
13486: @cindex @file{depth-changes.fs}
13487: @cindex depth changes during interpretation
13488: @cindex stack depth changes during interpretation
13489: @cindex items on the stack after interpretation
13490: 
13491: Sometimes you notice that, after loading a file, there are items left
13492: on the stack.  The tool @file{depth-changes.fs} helps you find out
13493: quickly where in the file these stack items are coming from.
13494: 
13495: The simplest way of using @file{depth-changes.fs} is to include it
13496: before the file(s) you want to check, e.g.:
13497: 
13498: @example
13499: gforth depth-changes.fs my-file.fs
13500: @end example
13501: 
13502: This will compare the stack depths of the data and FP stack at every
13503: empty line (in interpretation state) against these depths at the last
13504: empty line (in interpretation state).  If the depths are not equal,
13505: the position in the file and the stack contents are printed with
13506: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
13507: change has occured in the paragraph of non-empty lines before the
13508: indicated line.  It is a good idea to leave an empty line at the end
13509: of the file, so the last paragraph is checked, too.
13510: 
13511: Checking only at empty lines usually works well, but sometimes you
13512: have big blocks of non-empty lines (e.g., when building a big table),
13513: and you want to know where in this block the stack depth changed.  You
13514: can check all interpreted lines with
13515: 
13516: @example
13517: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13518: @end example
13519: 
13520: This checks the stack depth at every end-of-line.  So the depth change
13521: occured in the line reported by the @code{~~} (not in the line
13522: before).
13523: 
13524: Note that, while this offers better accuracy in indicating where the
13525: stack depth changes, it will often report many intentional stack depth
13526: changes (e.g., when an interpreted computation stretches across
13527: several lines).  You can suppress the checking of some lines by
13528: putting backslashes at the end of these lines (not followed by white
13529: space), and using
13530: 
13531: @example
13532: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13533: @end example
13534: 
13535: @c ******************************************************************
13536: @node ANS conformance, Standard vs Extensions, Tools, Top
13537: @chapter ANS conformance
13538: @cindex ANS conformance of Gforth
13539: 
13540: To the best of our knowledge, Gforth is an
13541: 
13542: ANS Forth System
13543: @itemize @bullet
13544: @item providing the Core Extensions word set
13545: @item providing the Block word set
13546: @item providing the Block Extensions word set
13547: @item providing the Double-Number word set
13548: @item providing the Double-Number Extensions word set
13549: @item providing the Exception word set
13550: @item providing the Exception Extensions word set
13551: @item providing the Facility word set
13552: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
13553: @item providing the File Access word set
13554: @item providing the File Access Extensions word set
13555: @item providing the Floating-Point word set
13556: @item providing the Floating-Point Extensions word set
13557: @item providing the Locals word set
13558: @item providing the Locals Extensions word set
13559: @item providing the Memory-Allocation word set
13560: @item providing the Memory-Allocation Extensions word set (that one's easy)
13561: @item providing the Programming-Tools word set
13562: @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
13563: @item providing the Search-Order word set
13564: @item providing the Search-Order Extensions word set
13565: @item providing the String word set
13566: @item providing the String Extensions word set (another easy one)
13567: @end itemize
13568: 
13569: Gforth has the following environmental restrictions:
13570: 
13571: @cindex environmental restrictions
13572: @itemize @bullet
13573: @item
13574: While processing the OS command line, if an exception is not caught,
13575: Gforth exits with a non-zero exit code instyead of performing QUIT.
13576: 
13577: @item
13578: When an @code{throw} is performed after a @code{query}, Gforth does not
13579: allways restore the input source specification in effect at the
13580: corresponding catch.
13581: 
13582: @end itemize
13583: 
13584: 
13585: @cindex system documentation
13586: In addition, ANS Forth systems are required to document certain
13587: implementation choices. This chapter tries to meet these
13588: requirements. In many cases it gives a way to ask the system for the
13589: information instead of providing the information directly, in
13590: particular, if the information depends on the processor, the operating
13591: system or the installation options chosen, or if they are likely to
13592: change during the maintenance of Gforth.
13593: 
13594: @comment The framework for the rest has been taken from pfe.
13595: 
13596: @menu
13597: * The Core Words::              
13598: * The optional Block word set::  
13599: * The optional Double Number word set::  
13600: * The optional Exception word set::  
13601: * The optional Facility word set::  
13602: * The optional File-Access word set::  
13603: * The optional Floating-Point word set::  
13604: * The optional Locals word set::  
13605: * The optional Memory-Allocation word set::  
13606: * The optional Programming-Tools word set::  
13607: * The optional Search-Order word set::  
13608: @end menu
13609: 
13610: 
13611: @c =====================================================================
13612: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13613: @comment  node-name,  next,  previous,  up
13614: @section The Core Words
13615: @c =====================================================================
13616: @cindex core words, system documentation
13617: @cindex system documentation, core words
13618: 
13619: @menu
13620: * core-idef::                   Implementation Defined Options                   
13621: * core-ambcond::                Ambiguous Conditions                
13622: * core-other::                  Other System Documentation                  
13623: @end menu
13624: 
13625: @c ---------------------------------------------------------------------
13626: @node core-idef, core-ambcond, The Core Words, The Core Words
13627: @subsection Implementation Defined Options
13628: @c ---------------------------------------------------------------------
13629: @cindex core words, implementation-defined options
13630: @cindex implementation-defined options, core words
13631: 
13632: 
13633: @table @i
13634: @item (Cell) aligned addresses:
13635: @cindex cell-aligned addresses
13636: @cindex aligned addresses
13637: processor-dependent. Gforth's alignment words perform natural alignment
13638: (e.g., an address aligned for a datum of size 8 is divisible by
13639: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13640: 
13641: @item @code{EMIT} and non-graphic characters:
13642: @cindex @code{EMIT} and non-graphic characters
13643: @cindex non-graphic characters and @code{EMIT}
13644: The character is output using the C library function (actually, macro)
13645: @code{putc}.
13646: 
13647: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13648: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13649: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13650: @cindex @code{ACCEPT}, editing
13651: @cindex @code{EXPECT}, editing
13652: This is modeled on the GNU readline library (@pxref{Readline
13653: Interaction, , Command Line Editing, readline, The GNU Readline
13654: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13655: producing a full word completion every time you type it (instead of
13656: producing the common prefix of all completions). @xref{Command-line editing}.
13657: 
13658: @item character set:
13659: @cindex character set
13660: The character set of your computer and display device. Gforth is
13661: 8-bit-clean (but some other component in your system may make trouble).
13662: 
13663: @item Character-aligned address requirements:
13664: @cindex character-aligned address requirements
13665: installation-dependent. Currently a character is represented by a C
13666: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13667: (Comments on that requested).
13668: 
13669: @item character-set extensions and matching of names:
13670: @cindex character-set extensions and matching of names
13671: @cindex case-sensitivity for name lookup
13672: @cindex name lookup, case-sensitivity
13673: @cindex locale and case-sensitivity
13674: Any character except the ASCII NUL character can be used in a
13675: name. Matching is case-insensitive (except in @code{TABLE}s). The
13676: matching is performed using the C library function @code{strncasecmp}, whose
13677: function is probably influenced by the locale. E.g., the @code{C} locale
13678: does not know about accents and umlauts, so they are matched
13679: case-sensitively in that locale. For portability reasons it is best to
13680: write programs such that they work in the @code{C} locale. Then one can
13681: use libraries written by a Polish programmer (who might use words
13682: containing ISO Latin-2 encoded characters) and by a French programmer
13683: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13684: funny results for some of the words (which ones, depends on the font you
13685: are using)). Also, the locale you prefer may not be available in other
13686: operating systems. Hopefully, Unicode will solve these problems one day.
13687: 
13688: @item conditions under which control characters match a space delimiter:
13689: @cindex space delimiters
13690: @cindex control characters as delimiters
13691: If @code{word} is called with the space character as a delimiter, all
13692: white-space characters (as identified by the C macro @code{isspace()})
13693: are delimiters. @code{Parse}, on the other hand, treats space like other
13694: delimiters.  @code{Parse-name}, which is used by the outer
13695: interpreter (aka text interpreter) by default, treats all white-space
13696: characters as delimiters.
13697: 
13698: @item format of the control-flow stack:
13699: @cindex control-flow stack, format
13700: The data stack is used as control-flow stack. The size of a control-flow
13701: stack item in cells is given by the constant @code{cs-item-size}. At the
13702: time of this writing, an item consists of a (pointer to a) locals list
13703: (third), an address in the code (second), and a tag for identifying the
13704: item (TOS). The following tags are used: @code{defstart},
13705: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13706: @code{scopestart}.
13707: 
13708: @item conversion of digits > 35
13709: @cindex digits > 35
13710: The characters @code{[\]^_'} are the digits with the decimal value
13711: 36@minus{}41. There is no way to input many of the larger digits.
13712: 
13713: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13714: @cindex @code{EXPECT}, display after end of input
13715: @cindex @code{ACCEPT}, display after end of input
13716: The cursor is moved to the end of the entered string. If the input is
13717: terminated using the @kbd{Return} key, a space is typed.
13718: 
13719: @item exception abort sequence of @code{ABORT"}:
13720: @cindex exception abort sequence of @code{ABORT"}
13721: @cindex @code{ABORT"}, exception abort sequence
13722: The error string is stored into the variable @code{"error} and a
13723: @code{-2 throw} is performed.
13724: 
13725: @item input line terminator:
13726: @cindex input line terminator
13727: @cindex line terminator on input
13728: @cindex newline character on input
13729: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13730: lines. One of these characters is typically produced when you type the
13731: @kbd{Enter} or @kbd{Return} key.
13732: 
13733: @item maximum size of a counted string:
13734: @cindex maximum size of a counted string
13735: @cindex counted string, maximum size
13736: @code{s" /counted-string" environment? drop .}. Currently 255 characters
13737: on all platforms, but this may change.
13738: 
13739: @item maximum size of a parsed string:
13740: @cindex maximum size of a parsed string
13741: @cindex parsed string, maximum size
13742: Given by the constant @code{/line}. Currently 255 characters.
13743: 
13744: @item maximum size of a definition name, in characters:
13745: @cindex maximum size of a definition name, in characters
13746: @cindex name, maximum length
13747: MAXU/8
13748: 
13749: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13750: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13751: @cindex @code{ENVIRONMENT?} string length, maximum
13752: MAXU/8
13753: 
13754: @item method of selecting the user input device:
13755: @cindex user input device, method of selecting
13756: The user input device is the standard input. There is currently no way to
13757: change it from within Gforth. However, the input can typically be
13758: redirected in the command line that starts Gforth.
13759: 
13760: @item method of selecting the user output device:
13761: @cindex user output device, method of selecting
13762: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
13763: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13764: output when the user output device is a terminal, otherwise the output
13765: is buffered.
13766: 
13767: @item methods of dictionary compilation:
13768: What are we expected to document here?
13769: 
13770: @item number of bits in one address unit:
13771: @cindex number of bits in one address unit
13772: @cindex address unit, size in bits
13773: @code{s" address-units-bits" environment? drop .}. 8 in all current
13774: platforms.
13775: 
13776: @item number representation and arithmetic:
13777: @cindex number representation and arithmetic
13778: Processor-dependent. Binary two's complement on all current platforms.
13779: 
13780: @item ranges for integer types:
13781: @cindex ranges for integer types
13782: @cindex integer types, ranges
13783: Installation-dependent. Make environmental queries for @code{MAX-N},
13784: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13785: unsigned (and positive) types is 0. The lower bound for signed types on
13786: two's complement and one's complement machines machines can be computed
13787: by adding 1 to the upper bound.
13788: 
13789: @item read-only data space regions:
13790: @cindex read-only data space regions
13791: @cindex data-space, read-only regions
13792: The whole Forth data space is writable.
13793: 
13794: @item size of buffer at @code{WORD}:
13795: @cindex size of buffer at @code{WORD}
13796: @cindex @code{WORD} buffer size
13797: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13798: shared with the pictured numeric output string. If overwriting
13799: @code{PAD} is acceptable, it is as large as the remaining dictionary
13800: space, although only as much can be sensibly used as fits in a counted
13801: string.
13802: 
13803: @item size of one cell in address units:
13804: @cindex cell size
13805: @code{1 cells .}.
13806: 
13807: @item size of one character in address units:
13808: @cindex char size
13809: @code{1 chars .}. 1 on all current platforms.
13810: 
13811: @item size of the keyboard terminal buffer:
13812: @cindex size of the keyboard terminal buffer
13813: @cindex terminal buffer, size
13814: Varies. You can determine the size at a specific time using @code{lp@@
13815: tib - .}. It is shared with the locals stack and TIBs of files that
13816: include the current file. You can change the amount of space for TIBs
13817: and locals stack at Gforth startup with the command line option
13818: @code{-l}.
13819: 
13820: @item size of the pictured numeric output buffer:
13821: @cindex size of the pictured numeric output buffer
13822: @cindex pictured numeric output buffer, size
13823: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13824: shared with @code{WORD}.
13825: 
13826: @item size of the scratch area returned by @code{PAD}:
13827: @cindex size of the scratch area returned by @code{PAD}
13828: @cindex @code{PAD} size
13829: The remainder of dictionary space. @code{unused pad here - - .}.
13830: 
13831: @item system case-sensitivity characteristics:
13832: @cindex case-sensitivity characteristics
13833: Dictionary searches are case-insensitive (except in
13834: @code{TABLE}s). However, as explained above under @i{character-set
13835: extensions}, the matching for non-ASCII characters is determined by the
13836: locale you are using. In the default @code{C} locale all non-ASCII
13837: characters are matched case-sensitively.
13838: 
13839: @item system prompt:
13840: @cindex system prompt
13841: @cindex prompt
13842: @code{ ok} in interpret state, @code{ compiled} in compile state.
13843: 
13844: @item division rounding:
13845: @cindex division rounding
13846: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13847: division (with the default installation of Gforth).  You can check
13848: this with @code{s" floored" environment? drop .}.  If you write
13849: programs that need a specific division rounding, best use
13850: @code{fm/mod} or @code{sm/rem} for portability.
13851: 
13852: @item values of @code{STATE} when true:
13853: @cindex @code{STATE} values
13854: -1.
13855: 
13856: @item values returned after arithmetic overflow:
13857: On two's complement machines, arithmetic is performed modulo
13858: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13859: arithmetic (with appropriate mapping for signed types). Division by
13860: zero typically results in a @code{-55 throw} (Floating-point
13861: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
13862: division overflow can result in these throws, or in @code{-11 throw};
13863: in @code{gforth-fast} division overflow and divide by zero may also
13864: result in returning bogus results without producing an exception.
13865: 
13866: @item whether the current definition can be found after @t{DOES>}:
13867: @cindex @t{DOES>}, visibility of current definition
13868: No.
13869: 
13870: @end table
13871: 
13872: @c ---------------------------------------------------------------------
13873: @node core-ambcond, core-other, core-idef, The Core Words
13874: @subsection Ambiguous conditions
13875: @c ---------------------------------------------------------------------
13876: @cindex core words, ambiguous conditions
13877: @cindex ambiguous conditions, core words
13878: 
13879: @table @i
13880: 
13881: @item a name is neither a word nor a number:
13882: @cindex name not found
13883: @cindex undefined word
13884: @code{-13 throw} (Undefined word).
13885: 
13886: @item a definition name exceeds the maximum length allowed:
13887: @cindex word name too long
13888: @code{-19 throw} (Word name too long)
13889: 
13890: @item addressing a region not inside the various data spaces of the forth system:
13891: @cindex Invalid memory address
13892: The stacks, code space and header space are accessible. Machine code space is
13893: typically readable. Accessing other addresses gives results dependent on
13894: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13895: address).
13896: 
13897: @item argument type incompatible with parameter:
13898: @cindex argument type mismatch
13899: This is usually not caught. Some words perform checks, e.g., the control
13900: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13901: mismatch).
13902: 
13903: @item attempting to obtain the execution token of a word with undefined execution semantics:
13904: @cindex Interpreting a compile-only word, for @code{'} etc.
13905: @cindex execution token of words with undefined execution semantics
13906: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13907: get an execution token for @code{compile-only-error} (which performs a
13908: @code{-14 throw} when executed).
13909: 
13910: @item dividing by zero:
13911: @cindex dividing by zero
13912: @cindex floating point unidentified fault, integer division
13913: On some platforms, this produces a @code{-10 throw} (Division by
13914: zero); on other systems, this typically results in a @code{-55 throw}
13915: (Floating-point unidentified fault).
13916: 
13917: @item insufficient data stack or return stack space:
13918: @cindex insufficient data stack or return stack space
13919: @cindex stack overflow
13920: @cindex address alignment exception, stack overflow
13921: @cindex Invalid memory address, stack overflow
13922: Depending on the operating system, the installation, and the invocation
13923: of Gforth, this is either checked by the memory management hardware, or
13924: it is not checked. If it is checked, you typically get a @code{-3 throw}
13925: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13926: throw} (Invalid memory address) (depending on the platform and how you
13927: achieved the overflow) as soon as the overflow happens. If it is not
13928: checked, overflows typically result in mysterious illegal memory
13929: accesses, producing @code{-9 throw} (Invalid memory address) or
13930: @code{-23 throw} (Address alignment exception); they might also destroy
13931: the internal data structure of @code{ALLOCATE} and friends, resulting in
13932: various errors in these words.
13933: 
13934: @item insufficient space for loop control parameters:
13935: @cindex insufficient space for loop control parameters
13936: Like other return stack overflows.
13937: 
13938: @item insufficient space in the dictionary:
13939: @cindex insufficient space in the dictionary
13940: @cindex dictionary overflow
13941: If you try to allot (either directly with @code{allot}, or indirectly
13942: with @code{,}, @code{create} etc.) more memory than available in the
13943: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13944: to access memory beyond the end of the dictionary, the results are
13945: similar to stack overflows.
13946: 
13947: @item interpreting a word with undefined interpretation semantics:
13948: @cindex interpreting a word with undefined interpretation semantics
13949: @cindex Interpreting a compile-only word
13950: For some words, we have defined interpretation semantics. For the
13951: others: @code{-14 throw} (Interpreting a compile-only word).
13952: 
13953: @item modifying the contents of the input buffer or a string literal:
13954: @cindex modifying the contents of the input buffer or a string literal
13955: These are located in writable memory and can be modified.
13956: 
13957: @item overflow of the pictured numeric output string:
13958: @cindex overflow of the pictured numeric output string
13959: @cindex pictured numeric output string, overflow
13960: @code{-17 throw} (Pictured numeric ouput string overflow).
13961: 
13962: @item parsed string overflow:
13963: @cindex parsed string overflow
13964: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13965: 
13966: @item producing a result out of range:
13967: @cindex result out of range
13968: On two's complement machines, arithmetic is performed modulo
13969: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13970: arithmetic (with appropriate mapping for signed types). Division by
13971: zero typically results in a @code{-10 throw} (divide by zero) or
13972: @code{-55 throw} (floating point unidentified fault). Overflow on
13973: division may result in these errors or in @code{-11 throw} (result out
13974: of range).  @code{Gforth-fast} may silently produce bogus results on
13975: division overflow or division by zero.  @code{Convert} and
13976: @code{>number} currently overflow silently.
13977: 
13978: @item reading from an empty data or return stack:
13979: @cindex stack empty
13980: @cindex stack underflow
13981: @cindex return stack underflow
13982: The data stack is checked by the outer (aka text) interpreter after
13983: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13984: underflow) is performed. Apart from that, stacks may be checked or not,
13985: depending on operating system, installation, and invocation. If they are
13986: caught by a check, they typically result in @code{-4 throw} (Stack
13987: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13988: (Invalid memory address), depending on the platform and which stack
13989: underflows and by how much. Note that even if the system uses checking
13990: (through the MMU), your program may have to underflow by a significant
13991: number of stack items to trigger the reaction (the reason for this is
13992: that the MMU, and therefore the checking, works with a page-size
13993: granularity).  If there is no checking, the symptoms resulting from an
13994: underflow are similar to those from an overflow.  Unbalanced return
13995: stack errors can result in a variety of symptoms, including @code{-9 throw}
13996: (Invalid memory address) and Illegal Instruction (typically @code{-260
13997: throw}).
13998: 
13999: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
14000: @cindex unexpected end of the input buffer
14001: @cindex zero-length string as a name
14002: @cindex Attempt to use zero-length string as a name
14003: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
14004: use zero-length string as a name). Words like @code{'} probably will not
14005: find what they search. Note that it is possible to create zero-length
14006: names with @code{nextname} (should it not?).
14007: 
14008: @item @code{>IN} greater than input buffer:
14009: @cindex @code{>IN} greater than input buffer
14010: The next invocation of a parsing word returns a string with length 0.
14011: 
14012: @item @code{RECURSE} appears after @code{DOES>}:
14013: @cindex @code{RECURSE} appears after @code{DOES>}
14014: Compiles a recursive call to the defining word, not to the defined word.
14015: 
14016: @item argument input source different than current input source for @code{RESTORE-INPUT}:
14017: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
14018: @cindex argument type mismatch, @code{RESTORE-INPUT}
14019: @cindex @code{RESTORE-INPUT}, Argument type mismatch
14020: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
14021: the end of the file was reached), its source-id may be
14022: reused. Therefore, restoring an input source specification referencing a
14023: closed file may lead to unpredictable results instead of a @code{-12
14024: THROW}.
14025: 
14026: In the future, Gforth may be able to restore input source specifications
14027: from other than the current input source.
14028: 
14029: @item data space containing definitions gets de-allocated:
14030: @cindex data space containing definitions gets de-allocated
14031: Deallocation with @code{allot} is not checked. This typically results in
14032: memory access faults or execution of illegal instructions.
14033: 
14034: @item data space read/write with incorrect alignment:
14035: @cindex data space read/write with incorrect alignment
14036: @cindex alignment faults
14037: @cindex address alignment exception
14038: Processor-dependent. Typically results in a @code{-23 throw} (Address
14039: alignment exception). Under Linux-Intel on a 486 or later processor with
14040: alignment turned on, incorrect alignment results in a @code{-9 throw}
14041: (Invalid memory address). There are reportedly some processors with
14042: alignment restrictions that do not report violations.
14043: 
14044: @item data space pointer not properly aligned, @code{,}, @code{C,}:
14045: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
14046: Like other alignment errors.
14047: 
14048: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
14049: Like other stack underflows.
14050: 
14051: @item loop control parameters not available:
14052: @cindex loop control parameters not available
14053: Not checked. The counted loop words simply assume that the top of return
14054: stack items are loop control parameters and behave accordingly.
14055: 
14056: @item most recent definition does not have a name (@code{IMMEDIATE}):
14057: @cindex most recent definition does not have a name (@code{IMMEDIATE})
14058: @cindex last word was headerless
14059: @code{abort" last word was headerless"}.
14060: 
14061: @item name not defined by @code{VALUE} used by @code{TO}:
14062: @cindex name not defined by @code{VALUE} used by @code{TO}
14063: @cindex @code{TO} on non-@code{VALUE}s
14064: @cindex Invalid name argument, @code{TO}
14065: @code{-32 throw} (Invalid name argument) (unless name is a local or was
14066: defined by @code{CONSTANT}; in the latter case it just changes the constant).
14067: 
14068: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
14069: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
14070: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
14071: @code{-13 throw} (Undefined word)
14072: 
14073: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
14074: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
14075: Gforth behaves as if they were of the same type. I.e., you can predict
14076: the behaviour by interpreting all parameters as, e.g., signed.
14077: 
14078: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
14079: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
14080: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
14081: compilation semantics of @code{TO}.
14082: 
14083: @item String longer than a counted string returned by @code{WORD}:
14084: @cindex string longer than a counted string returned by @code{WORD}
14085: @cindex @code{WORD}, string overflow
14086: Not checked. The string will be ok, but the count will, of course,
14087: contain only the least significant bits of the length.
14088: 
14089: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
14090: @cindex @code{LSHIFT}, large shift counts
14091: @cindex @code{RSHIFT}, large shift counts
14092: Processor-dependent. Typical behaviours are returning 0 and using only
14093: the low bits of the shift count.
14094: 
14095: @item word not defined via @code{CREATE}:
14096: @cindex @code{>BODY} of non-@code{CREATE}d words
14097: @code{>BODY} produces the PFA of the word no matter how it was defined.
14098: 
14099: @cindex @code{DOES>} of non-@code{CREATE}d words
14100: @code{DOES>} changes the execution semantics of the last defined word no
14101: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
14102: @code{CREATE , DOES>}.
14103: 
14104: @item words improperly used outside @code{<#} and @code{#>}:
14105: Not checked. As usual, you can expect memory faults.
14106: 
14107: @end table
14108: 
14109: 
14110: @c ---------------------------------------------------------------------
14111: @node core-other,  , core-ambcond, The Core Words
14112: @subsection Other system documentation
14113: @c ---------------------------------------------------------------------
14114: @cindex other system documentation, core words
14115: @cindex core words, other system documentation
14116: 
14117: @table @i
14118: @item nonstandard words using @code{PAD}:
14119: @cindex @code{PAD} use by nonstandard words
14120: None.
14121: 
14122: @item operator's terminal facilities available:
14123: @cindex operator's terminal facilities available
14124: After processing the OS's command line, Gforth goes into interactive mode,
14125: and you can give commands to Gforth interactively. The actual facilities
14126: available depend on how you invoke Gforth.
14127: 
14128: @item program data space available:
14129: @cindex program data space available
14130: @cindex data space available
14131: @code{UNUSED .} gives the remaining dictionary space. The total
14132: dictionary space can be specified with the @code{-m} switch
14133: (@pxref{Invoking Gforth}) when Gforth starts up.
14134: 
14135: @item return stack space available:
14136: @cindex return stack space available
14137: You can compute the total return stack space in cells with
14138: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
14139: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
14140: 
14141: @item stack space available:
14142: @cindex stack space available
14143: You can compute the total data stack space in cells with
14144: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
14145: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
14146: 
14147: @item system dictionary space required, in address units:
14148: @cindex system dictionary space required, in address units
14149: Type @code{here forthstart - .} after startup. At the time of this
14150: writing, this gives 80080 (bytes) on a 32-bit system.
14151: @end table
14152: 
14153: 
14154: @c =====================================================================
14155: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
14156: @section The optional Block word set
14157: @c =====================================================================
14158: @cindex system documentation, block words
14159: @cindex block words, system documentation
14160: 
14161: @menu
14162: * block-idef::                  Implementation Defined Options
14163: * block-ambcond::               Ambiguous Conditions               
14164: * block-other::                 Other System Documentation                 
14165: @end menu
14166: 
14167: 
14168: @c ---------------------------------------------------------------------
14169: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
14170: @subsection Implementation Defined Options
14171: @c ---------------------------------------------------------------------
14172: @cindex implementation-defined options, block words
14173: @cindex block words, implementation-defined options
14174: 
14175: @table @i
14176: @item the format for display by @code{LIST}:
14177: @cindex @code{LIST} display format
14178: First the screen number is displayed, then 16 lines of 64 characters,
14179: each line preceded by the line number.
14180: 
14181: @item the length of a line affected by @code{\}:
14182: @cindex length of a line affected by @code{\}
14183: @cindex @code{\}, line length in blocks
14184: 64 characters.
14185: @end table
14186: 
14187: 
14188: @c ---------------------------------------------------------------------
14189: @node block-ambcond, block-other, block-idef, The optional Block word set
14190: @subsection Ambiguous conditions
14191: @c ---------------------------------------------------------------------
14192: @cindex block words, ambiguous conditions
14193: @cindex ambiguous conditions, block words
14194: 
14195: @table @i
14196: @item correct block read was not possible:
14197: @cindex block read not possible
14198: Typically results in a @code{throw} of some OS-derived value (between
14199: -512 and -2048). If the blocks file was just not long enough, blanks are
14200: supplied for the missing portion.
14201: 
14202: @item I/O exception in block transfer:
14203: @cindex I/O exception in block transfer
14204: @cindex block transfer, I/O exception
14205: Typically results in a @code{throw} of some OS-derived value (between
14206: -512 and -2048).
14207: 
14208: @item invalid block number:
14209: @cindex invalid block number
14210: @cindex block number invalid
14211: @code{-35 throw} (Invalid block number)
14212: 
14213: @item a program directly alters the contents of @code{BLK}:
14214: @cindex @code{BLK}, altering @code{BLK}
14215: The input stream is switched to that other block, at the same
14216: position. If the storing to @code{BLK} happens when interpreting
14217: non-block input, the system will get quite confused when the block ends.
14218: 
14219: @item no current block buffer for @code{UPDATE}:
14220: @cindex @code{UPDATE}, no current block buffer
14221: @code{UPDATE} has no effect.
14222: 
14223: @end table
14224: 
14225: @c ---------------------------------------------------------------------
14226: @node block-other,  , block-ambcond, The optional Block word set
14227: @subsection Other system documentation
14228: @c ---------------------------------------------------------------------
14229: @cindex other system documentation, block words
14230: @cindex block words, other system documentation
14231: 
14232: @table @i
14233: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14234: No restrictions (yet).
14235: 
14236: @item the number of blocks available for source and data:
14237: depends on your disk space.
14238: 
14239: @end table
14240: 
14241: 
14242: @c =====================================================================
14243: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14244: @section The optional Double Number word set
14245: @c =====================================================================
14246: @cindex system documentation, double words
14247: @cindex double words, system documentation
14248: 
14249: @menu
14250: * double-ambcond::              Ambiguous Conditions              
14251: @end menu
14252: 
14253: 
14254: @c ---------------------------------------------------------------------
14255: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
14256: @subsection Ambiguous conditions
14257: @c ---------------------------------------------------------------------
14258: @cindex double words, ambiguous conditions
14259: @cindex ambiguous conditions, double words
14260: 
14261: @table @i
14262: @item @i{d} outside of range of @i{n} in @code{D>S}:
14263: @cindex @code{D>S}, @i{d} out of range of @i{n} 
14264: The least significant cell of @i{d} is produced.
14265: 
14266: @end table
14267: 
14268: 
14269: @c =====================================================================
14270: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14271: @section The optional Exception word set
14272: @c =====================================================================
14273: @cindex system documentation, exception words
14274: @cindex exception words, system documentation
14275: 
14276: @menu
14277: * exception-idef::              Implementation Defined Options              
14278: @end menu
14279: 
14280: 
14281: @c ---------------------------------------------------------------------
14282: @node exception-idef,  , The optional Exception word set, The optional Exception word set
14283: @subsection Implementation Defined Options
14284: @c ---------------------------------------------------------------------
14285: @cindex implementation-defined options, exception words
14286: @cindex exception words, implementation-defined options
14287: 
14288: @table @i
14289: @item @code{THROW}-codes used in the system:
14290: @cindex @code{THROW}-codes used in the system
14291: The codes -256@minus{}-511 are used for reporting signals. The mapping
14292: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
14293: codes -512@minus{}-2047 are used for OS errors (for file and memory
14294: allocation operations). The mapping from OS error numbers to throw codes
14295: is -512@minus{}@code{errno}. One side effect of this mapping is that
14296: undefined OS errors produce a message with a strange number; e.g.,
14297: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14298: @end table
14299: 
14300: @c =====================================================================
14301: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14302: @section The optional Facility word set
14303: @c =====================================================================
14304: @cindex system documentation, facility words
14305: @cindex facility words, system documentation
14306: 
14307: @menu
14308: * facility-idef::               Implementation Defined Options               
14309: * facility-ambcond::            Ambiguous Conditions            
14310: @end menu
14311: 
14312: 
14313: @c ---------------------------------------------------------------------
14314: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14315: @subsection Implementation Defined Options
14316: @c ---------------------------------------------------------------------
14317: @cindex implementation-defined options, facility words
14318: @cindex facility words, implementation-defined options
14319: 
14320: @table @i
14321: @item encoding of keyboard events (@code{EKEY}):
14322: @cindex keyboard events, encoding in @code{EKEY}
14323: @cindex @code{EKEY}, encoding of keyboard events
14324: Keys corresponding to ASCII characters are encoded as ASCII characters.
14325: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14326: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14327: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14328: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
14329: 
14330: 
14331: @item duration of a system clock tick:
14332: @cindex duration of a system clock tick
14333: @cindex clock tick duration
14334: System dependent. With respect to @code{MS}, the time is specified in
14335: microseconds. How well the OS and the hardware implement this, is
14336: another question.
14337: 
14338: @item repeatability to be expected from the execution of @code{MS}:
14339: @cindex repeatability to be expected from the execution of @code{MS}
14340: @cindex @code{MS}, repeatability to be expected
14341: System dependent. On Unix, a lot depends on load. If the system is
14342: lightly loaded, and the delay is short enough that Gforth does not get
14343: swapped out, the performance should be acceptable. Under MS-DOS and
14344: other single-tasking systems, it should be good.
14345: 
14346: @end table
14347: 
14348: 
14349: @c ---------------------------------------------------------------------
14350: @node facility-ambcond,  , facility-idef, The optional Facility word set
14351: @subsection Ambiguous conditions
14352: @c ---------------------------------------------------------------------
14353: @cindex facility words, ambiguous conditions
14354: @cindex ambiguous conditions, facility words
14355: 
14356: @table @i
14357: @item @code{AT-XY} can't be performed on user output device:
14358: @cindex @code{AT-XY} can't be performed on user output device
14359: Largely terminal dependent. No range checks are done on the arguments.
14360: No errors are reported. You may see some garbage appearing, you may see
14361: simply nothing happen.
14362: 
14363: @end table
14364: 
14365: 
14366: @c =====================================================================
14367: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14368: @section The optional File-Access word set
14369: @c =====================================================================
14370: @cindex system documentation, file words
14371: @cindex file words, system documentation
14372: 
14373: @menu
14374: * file-idef::                   Implementation Defined Options
14375: * file-ambcond::                Ambiguous Conditions                
14376: @end menu
14377: 
14378: @c ---------------------------------------------------------------------
14379: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14380: @subsection Implementation Defined Options
14381: @c ---------------------------------------------------------------------
14382: @cindex implementation-defined options, file words
14383: @cindex file words, implementation-defined options
14384: 
14385: @table @i
14386: @item file access methods used:
14387: @cindex file access methods used
14388: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14389: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14390: @code{wb}): The file is cleared, if it exists, and created, if it does
14391: not (with both @code{open-file} and @code{create-file}).  Under Unix
14392: @code{create-file} creates a file with 666 permissions modified by your
14393: umask.
14394: 
14395: @item file exceptions:
14396: @cindex file exceptions
14397: The file words do not raise exceptions (except, perhaps, memory access
14398: faults when you pass illegal addresses or file-ids).
14399: 
14400: @item file line terminator:
14401: @cindex file line terminator
14402: System-dependent. Gforth uses C's newline character as line
14403: terminator. What the actual character code(s) of this are is
14404: system-dependent.
14405: 
14406: @item file name format:
14407: @cindex file name format
14408: System dependent. Gforth just uses the file name format of your OS.
14409: 
14410: @item information returned by @code{FILE-STATUS}:
14411: @cindex @code{FILE-STATUS}, returned information
14412: @code{FILE-STATUS} returns the most powerful file access mode allowed
14413: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14414: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14415: along with the returned mode.
14416: 
14417: @item input file state after an exception when including source:
14418: @cindex exception when including source
14419: All files that are left via the exception are closed.
14420: 
14421: @item @i{ior} values and meaning:
14422: @cindex @i{ior} values and meaning
14423: @cindex @i{wior} values and meaning
14424: The @i{ior}s returned by the file and memory allocation words are
14425: intended as throw codes. They typically are in the range
14426: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14427: @i{ior}s is -512@minus{}@i{errno}.
14428: 
14429: @item maximum depth of file input nesting:
14430: @cindex maximum depth of file input nesting
14431: @cindex file input nesting, maximum depth
14432: limited by the amount of return stack, locals/TIB stack, and the number
14433: of open files available. This should not give you troubles.
14434: 
14435: @item maximum size of input line:
14436: @cindex maximum size of input line
14437: @cindex input line size, maximum
14438: @code{/line}. Currently 255.
14439: 
14440: @item methods of mapping block ranges to files:
14441: @cindex mapping block ranges to files
14442: @cindex files containing blocks
14443: @cindex blocks in files
14444: By default, blocks are accessed in the file @file{blocks.fb} in the
14445: current working directory. The file can be switched with @code{USE}.
14446: 
14447: @item number of string buffers provided by @code{S"}:
14448: @cindex @code{S"}, number of string buffers
14449: 1
14450: 
14451: @item size of string buffer used by @code{S"}:
14452: @cindex @code{S"}, size of string buffer
14453: @code{/line}. currently 255.
14454: 
14455: @end table
14456: 
14457: @c ---------------------------------------------------------------------
14458: @node file-ambcond,  , file-idef, The optional File-Access word set
14459: @subsection Ambiguous conditions
14460: @c ---------------------------------------------------------------------
14461: @cindex file words, ambiguous conditions
14462: @cindex ambiguous conditions, file words
14463: 
14464: @table @i
14465: @item attempting to position a file outside its boundaries:
14466: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14467: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14468: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14469: 
14470: @item attempting to read from file positions not yet written:
14471: @cindex reading from file positions not yet written
14472: End-of-file, i.e., zero characters are read and no error is reported.
14473: 
14474: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14475: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
14476: An appropriate exception may be thrown, but a memory fault or other
14477: problem is more probable.
14478: 
14479: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14480: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14481: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14482: The @i{ior} produced by the operation, that discovered the problem, is
14483: thrown.
14484: 
14485: @item named file cannot be opened (@code{INCLUDED}):
14486: @cindex @code{INCLUDED}, named file cannot be opened
14487: The @i{ior} produced by @code{open-file} is thrown.
14488: 
14489: @item requesting an unmapped block number:
14490: @cindex unmapped block numbers
14491: There are no unmapped legal block numbers. On some operating systems,
14492: writing a block with a large number may overflow the file system and
14493: have an error message as consequence.
14494: 
14495: @item using @code{source-id} when @code{blk} is non-zero:
14496: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14497: @code{source-id} performs its function. Typically it will give the id of
14498: the source which loaded the block. (Better ideas?)
14499: 
14500: @end table
14501: 
14502: 
14503: @c =====================================================================
14504: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14505: @section The optional Floating-Point word set
14506: @c =====================================================================
14507: @cindex system documentation, floating-point words
14508: @cindex floating-point words, system documentation
14509: 
14510: @menu
14511: * floating-idef::               Implementation Defined Options
14512: * floating-ambcond::            Ambiguous Conditions            
14513: @end menu
14514: 
14515: 
14516: @c ---------------------------------------------------------------------
14517: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14518: @subsection Implementation Defined Options
14519: @c ---------------------------------------------------------------------
14520: @cindex implementation-defined options, floating-point words
14521: @cindex floating-point words, implementation-defined options
14522: 
14523: @table @i
14524: @item format and range of floating point numbers:
14525: @cindex format and range of floating point numbers
14526: @cindex floating point numbers, format and range
14527: System-dependent; the @code{double} type of C.
14528: 
14529: @item results of @code{REPRESENT} when @i{float} is out of range:
14530: @cindex  @code{REPRESENT}, results when @i{float} is out of range
14531: System dependent; @code{REPRESENT} is implemented using the C library
14532: function @code{ecvt()} and inherits its behaviour in this respect.
14533: 
14534: @item rounding or truncation of floating-point numbers:
14535: @cindex rounding of floating-point numbers
14536: @cindex truncation of floating-point numbers
14537: @cindex floating-point numbers, rounding or truncation
14538: System dependent; the rounding behaviour is inherited from the hosting C
14539: compiler. IEEE-FP-based (i.e., most) systems by default round to
14540: nearest, and break ties by rounding to even (i.e., such that the last
14541: bit of the mantissa is 0).
14542: 
14543: @item size of floating-point stack:
14544: @cindex floating-point stack size
14545: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14546: the floating-point stack (in floats). You can specify this on startup
14547: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14548: 
14549: @item width of floating-point stack:
14550: @cindex floating-point stack width 
14551: @code{1 floats}.
14552: 
14553: @end table
14554: 
14555: 
14556: @c ---------------------------------------------------------------------
14557: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
14558: @subsection Ambiguous conditions
14559: @c ---------------------------------------------------------------------
14560: @cindex floating-point words, ambiguous conditions
14561: @cindex ambiguous conditions, floating-point words
14562: 
14563: @table @i
14564: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
14565: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
14566: System-dependent. Typically results in a @code{-23 THROW} like other
14567: alignment violations.
14568: 
14569: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
14570: @cindex @code{f@@} used with an address that is not float aligned
14571: @cindex @code{f!} used with an address that is not float aligned
14572: System-dependent. Typically results in a @code{-23 THROW} like other
14573: alignment violations.
14574: 
14575: @item floating-point result out of range:
14576: @cindex floating-point result out of range
14577: System-dependent. Can result in a @code{-43 throw} (floating point
14578: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14579: (floating point inexact result), @code{-55 THROW} (Floating-point
14580: unidentified fault), or can produce a special value representing, e.g.,
14581: Infinity.
14582: 
14583: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
14584: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
14585: System-dependent. Typically results in an alignment fault like other
14586: alignment violations.
14587: 
14588: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14589: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
14590: The floating-point number is converted into decimal nonetheless.
14591: 
14592: @item Both arguments are equal to zero (@code{FATAN2}):
14593: @cindex @code{FATAN2}, both arguments are equal to zero
14594: System-dependent. @code{FATAN2} is implemented using the C library
14595: function @code{atan2()}.
14596: 
14597: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14598: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14599: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
14600: because of small errors and the tan will be a very large (or very small)
14601: but finite number.
14602: 
14603: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14604: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
14605: The result is rounded to the nearest float.
14606: 
14607: @item dividing by zero:
14608: @cindex dividing by zero, floating-point
14609: @cindex floating-point dividing by zero
14610: @cindex floating-point unidentified fault, FP divide-by-zero
14611: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14612: (floating point divide by zero) or @code{-55 throw} (Floating-point
14613: unidentified fault).
14614: 
14615: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14616: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14617: System dependent. On IEEE-FP based systems the number is converted into
14618: an infinity.
14619: 
14620: @item @i{float}<1 (@code{FACOSH}):
14621: @cindex @code{FACOSH}, @i{float}<1
14622: @cindex floating-point unidentified fault, @code{FACOSH}
14623: Platform-dependent; on IEEE-FP systems typically produces a NaN.
14624: 
14625: @item @i{float}=<-1 (@code{FLNP1}):
14626: @cindex @code{FLNP1}, @i{float}=<-1
14627: @cindex floating-point unidentified fault, @code{FLNP1}
14628: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14629: negative infinity for @i{float}=-1).
14630: 
14631: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14632: @cindex @code{FLN}, @i{float}=<0
14633: @cindex @code{FLOG}, @i{float}=<0
14634: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
14635: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14636: negative infinity for @i{float}=0).
14637: 
14638: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14639: @cindex @code{FASINH}, @i{float}<0
14640: @cindex @code{FSQRT}, @i{float}<0
14641: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
14642: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14643: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14644: C library?).
14645: 
14646: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14647: @cindex @code{FACOS}, |@i{float}|>1
14648: @cindex @code{FASIN}, |@i{float}|>1
14649: @cindex @code{FATANH}, |@i{float}|>1
14650: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
14651: Platform-dependent; IEEE-FP systems typically produce a NaN.
14652: 
14653: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14654: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
14655: @cindex floating-point unidentified fault, @code{F>D}
14656: Platform-dependent; typically, some double number is produced and no
14657: error is reported.
14658: 
14659: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14660: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
14661: @code{Precision} characters of the numeric output area are used.  If
14662: @code{precision} is too high, these words will smash the data or code
14663: close to @code{here}.
14664: @end table
14665: 
14666: @c =====================================================================
14667: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14668: @section The optional Locals word set
14669: @c =====================================================================
14670: @cindex system documentation, locals words
14671: @cindex locals words, system documentation
14672: 
14673: @menu
14674: * locals-idef::                 Implementation Defined Options                 
14675: * locals-ambcond::              Ambiguous Conditions              
14676: @end menu
14677: 
14678: 
14679: @c ---------------------------------------------------------------------
14680: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14681: @subsection Implementation Defined Options
14682: @c ---------------------------------------------------------------------
14683: @cindex implementation-defined options, locals words
14684: @cindex locals words, implementation-defined options
14685: 
14686: @table @i
14687: @item maximum number of locals in a definition:
14688: @cindex maximum number of locals in a definition
14689: @cindex locals, maximum number in a definition
14690: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14691: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14692: characters. The number of locals in a definition is bounded by the size
14693: of locals-buffer, which contains the names of the locals.
14694: 
14695: @end table
14696: 
14697: 
14698: @c ---------------------------------------------------------------------
14699: @node locals-ambcond,  , locals-idef, The optional Locals word set
14700: @subsection Ambiguous conditions
14701: @c ---------------------------------------------------------------------
14702: @cindex locals words, ambiguous conditions
14703: @cindex ambiguous conditions, locals words
14704: 
14705: @table @i
14706: @item executing a named local in interpretation state:
14707: @cindex local in interpretation state
14708: @cindex Interpreting a compile-only word, for a local
14709: Locals have no interpretation semantics. If you try to perform the
14710: interpretation semantics, you will get a @code{-14 throw} somewhere
14711: (Interpreting a compile-only word). If you perform the compilation
14712: semantics, the locals access will be compiled (irrespective of state).
14713: 
14714: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
14715: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14716: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14717: @cindex Invalid name argument, @code{TO}
14718: @code{-32 throw} (Invalid name argument)
14719: 
14720: @end table
14721: 
14722: 
14723: @c =====================================================================
14724: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14725: @section The optional Memory-Allocation word set
14726: @c =====================================================================
14727: @cindex system documentation, memory-allocation words
14728: @cindex memory-allocation words, system documentation
14729: 
14730: @menu
14731: * memory-idef::                 Implementation Defined Options                 
14732: @end menu
14733: 
14734: 
14735: @c ---------------------------------------------------------------------
14736: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14737: @subsection Implementation Defined Options
14738: @c ---------------------------------------------------------------------
14739: @cindex implementation-defined options, memory-allocation words
14740: @cindex memory-allocation words, implementation-defined options
14741: 
14742: @table @i
14743: @item values and meaning of @i{ior}:
14744: @cindex  @i{ior} values and meaning
14745: The @i{ior}s returned by the file and memory allocation words are
14746: intended as throw codes. They typically are in the range
14747: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14748: @i{ior}s is -512@minus{}@i{errno}.
14749: 
14750: @end table
14751: 
14752: @c =====================================================================
14753: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14754: @section The optional Programming-Tools word set
14755: @c =====================================================================
14756: @cindex system documentation, programming-tools words
14757: @cindex programming-tools words, system documentation
14758: 
14759: @menu
14760: * programming-idef::            Implementation Defined Options            
14761: * programming-ambcond::         Ambiguous Conditions         
14762: @end menu
14763: 
14764: 
14765: @c ---------------------------------------------------------------------
14766: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14767: @subsection Implementation Defined Options
14768: @c ---------------------------------------------------------------------
14769: @cindex implementation-defined options, programming-tools words
14770: @cindex programming-tools words, implementation-defined options
14771: 
14772: @table @i
14773: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14774: @cindex @code{;CODE} ending sequence
14775: @cindex @code{CODE} ending sequence
14776: @code{END-CODE}
14777: 
14778: @item manner of processing input following @code{;CODE} and @code{CODE}:
14779: @cindex @code{;CODE}, processing input
14780: @cindex @code{CODE}, processing input
14781: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14782: the input is processed by the text interpreter, (starting) in interpret
14783: state.
14784: 
14785: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14786: @cindex @code{ASSEMBLER}, search order capability
14787: The ANS Forth search order word set.
14788: 
14789: @item source and format of display by @code{SEE}:
14790: @cindex @code{SEE}, source and format of output
14791: The source for @code{see} is the executable code used by the inner
14792: interpreter.  The current @code{see} tries to output Forth source code
14793: (and on some platforms, assembly code for primitives) as well as
14794: possible.
14795: 
14796: @end table
14797: 
14798: @c ---------------------------------------------------------------------
14799: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
14800: @subsection Ambiguous conditions
14801: @c ---------------------------------------------------------------------
14802: @cindex programming-tools words, ambiguous conditions
14803: @cindex ambiguous conditions, programming-tools words
14804: 
14805: @table @i
14806: 
14807: @item deleting the compilation word list (@code{FORGET}):
14808: @cindex @code{FORGET}, deleting the compilation word list
14809: Not implemented (yet).
14810: 
14811: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14812: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14813: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
14814: @cindex control-flow stack underflow
14815: This typically results in an @code{abort"} with a descriptive error
14816: message (may change into a @code{-22 throw} (Control structure mismatch)
14817: in the future). You may also get a memory access error. If you are
14818: unlucky, this ambiguous condition is not caught.
14819: 
14820: @item @i{name} can't be found (@code{FORGET}):
14821: @cindex @code{FORGET}, @i{name} can't be found
14822: Not implemented (yet).
14823: 
14824: @item @i{name} not defined via @code{CREATE}:
14825: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
14826: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14827: the execution semantics of the last defined word no matter how it was
14828: defined.
14829: 
14830: @item @code{POSTPONE} applied to @code{[IF]}:
14831: @cindex @code{POSTPONE} applied to @code{[IF]}
14832: @cindex @code{[IF]} and @code{POSTPONE}
14833: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14834: equivalent to @code{[IF]}.
14835: 
14836: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14837: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14838: Continue in the same state of conditional compilation in the next outer
14839: input source. Currently there is no warning to the user about this.
14840: 
14841: @item removing a needed definition (@code{FORGET}):
14842: @cindex @code{FORGET}, removing a needed definition
14843: Not implemented (yet).
14844: 
14845: @end table
14846: 
14847: 
14848: @c =====================================================================
14849: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
14850: @section The optional Search-Order word set
14851: @c =====================================================================
14852: @cindex system documentation, search-order words
14853: @cindex search-order words, system documentation
14854: 
14855: @menu
14856: * search-idef::                 Implementation Defined Options                 
14857: * search-ambcond::              Ambiguous Conditions              
14858: @end menu
14859: 
14860: 
14861: @c ---------------------------------------------------------------------
14862: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14863: @subsection Implementation Defined Options
14864: @c ---------------------------------------------------------------------
14865: @cindex implementation-defined options, search-order words
14866: @cindex search-order words, implementation-defined options
14867: 
14868: @table @i
14869: @item maximum number of word lists in search order:
14870: @cindex maximum number of word lists in search order
14871: @cindex search order, maximum depth
14872: @code{s" wordlists" environment? drop .}. Currently 16.
14873: 
14874: @item minimum search order:
14875: @cindex minimum search order
14876: @cindex search order, minimum
14877: @code{root root}.
14878: 
14879: @end table
14880: 
14881: @c ---------------------------------------------------------------------
14882: @node search-ambcond,  , search-idef, The optional Search-Order word set
14883: @subsection Ambiguous conditions
14884: @c ---------------------------------------------------------------------
14885: @cindex search-order words, ambiguous conditions
14886: @cindex ambiguous conditions, search-order words
14887: 
14888: @table @i
14889: @item changing the compilation word list (during compilation):
14890: @cindex changing the compilation word list (during compilation)
14891: @cindex compilation word list, change before definition ends
14892: The word is entered into the word list that was the compilation word list
14893: at the start of the definition. Any changes to the name field (e.g.,
14894: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
14895: are applied to the latest defined word (as reported by @code{latest} or
14896: @code{latestxt}), if possible, irrespective of the compilation word list.
14897: 
14898: @item search order empty (@code{previous}):
14899: @cindex @code{previous}, search order empty
14900: @cindex vocstack empty, @code{previous}
14901: @code{abort" Vocstack empty"}.
14902: 
14903: @item too many word lists in search order (@code{also}):
14904: @cindex @code{also}, too many word lists in search order
14905: @cindex vocstack full, @code{also}
14906: @code{abort" Vocstack full"}.
14907: 
14908: @end table
14909: 
14910: @c ***************************************************************
14911: @node Standard vs Extensions, Model, ANS conformance, Top
14912: @chapter Should I use Gforth extensions?
14913: @cindex Gforth extensions
14914: 
14915: As you read through the rest of this manual, you will see documentation
14916: for @i{Standard} words, and documentation for some appealing Gforth
14917: @i{extensions}. You might ask yourself the question: @i{``Should I
14918: restrict myself to the standard, or should I use the extensions?''}
14919: 
14920: The answer depends on the goals you have for the program you are working
14921: on:
14922: 
14923: @itemize @bullet
14924: 
14925: @item Is it just for yourself or do you want to share it with others?
14926: 
14927: @item
14928: If you want to share it, do the others all use Gforth?
14929: 
14930: @item
14931: If it is just for yourself, do you want to restrict yourself to Gforth?
14932: 
14933: @end itemize
14934: 
14935: If restricting the program to Gforth is ok, then there is no reason not
14936: to use extensions.  It is still a good idea to keep to the standard
14937: where it is easy, in case you want to reuse these parts in another
14938: program that you want to be portable.
14939: 
14940: If you want to be able to port the program to other Forth systems, there
14941: are the following points to consider:
14942: 
14943: @itemize @bullet
14944: 
14945: @item
14946: Most Forth systems that are being maintained support the ANS Forth
14947: standard.  So if your program complies with the standard, it will be
14948: portable among many systems.
14949: 
14950: @item
14951: A number of the Gforth extensions can be implemented in ANS Forth using
14952: public-domain files provided in the @file{compat/} directory. These are
14953: mentioned in the text in passing.  There is no reason not to use these
14954: extensions, your program will still be ANS Forth compliant; just include
14955: the appropriate compat files with your program.
14956: 
14957: @item
14958: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14959: analyse your program and determine what non-Standard words it relies
14960: upon.  However, it does not check whether you use standard words in a
14961: non-standard way.
14962: 
14963: @item
14964: Some techniques are not standardized by ANS Forth, and are hard or
14965: impossible to implement in a standard way, but can be implemented in
14966: most Forth systems easily, and usually in similar ways (e.g., accessing
14967: word headers).  Forth has a rich historical precedent for programmers
14968: taking advantage of implementation-dependent features of their tools
14969: (for example, relying on a knowledge of the dictionary
14970: structure). Sometimes these techniques are necessary to extract every
14971: last bit of performance from the hardware, sometimes they are just a
14972: programming shorthand.
14973: 
14974: @item
14975: Does using a Gforth extension save more work than the porting this part
14976: to other Forth systems (if any) will cost?
14977: 
14978: @item
14979: Is the additional functionality worth the reduction in portability and
14980: the additional porting problems?
14981: 
14982: @end itemize
14983: 
14984: In order to perform these consideratios, you need to know what's
14985: standard and what's not.  This manual generally states if something is
14986: non-standard, but the authoritative source is the
14987: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
14988: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14989: into the thought processes of the technical committee.
14990: 
14991: Note also that portability between Forth systems is not the only
14992: portability issue; there is also the issue of portability between
14993: different platforms (processor/OS combinations).
14994: 
14995: @c ***************************************************************
14996: @node Model, Integrating Gforth, Standard vs Extensions, Top
14997: @chapter Model
14998: 
14999: This chapter has yet to be written. It will contain information, on
15000: which internal structures you can rely.
15001: 
15002: @c ***************************************************************
15003: @node Integrating Gforth, Emacs and Gforth, Model, Top
15004: @chapter Integrating Gforth into C programs
15005: 
15006: This is not yet implemented.
15007: 
15008: Several people like to use Forth as scripting language for applications
15009: that are otherwise written in C, C++, or some other language.
15010: 
15011: The Forth system ATLAST provides facilities for embedding it into
15012: applications; unfortunately it has several disadvantages: most
15013: importantly, it is not based on ANS Forth, and it is apparently dead
15014: (i.e., not developed further and not supported). The facilities
15015: provided by Gforth in this area are inspired by ATLAST's facilities, so
15016: making the switch should not be hard.
15017: 
15018: We also tried to design the interface such that it can easily be
15019: implemented by other Forth systems, so that we may one day arrive at a
15020: standardized interface. Such a standard interface would allow you to
15021: replace the Forth system without having to rewrite C code.
15022: 
15023: You embed the Gforth interpreter by linking with the library
15024: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
15025: global symbols in this library that belong to the interface, have the
15026: prefix @code{forth_}. (Global symbols that are used internally have the
15027: prefix @code{gforth_}).
15028: 
15029: You can include the declarations of Forth types and the functions and
15030: variables of the interface with @code{#include <forth.h>}.
15031: 
15032: Types.
15033: 
15034: Variables.
15035: 
15036: Data and FP Stack pointer. Area sizes.
15037: 
15038: functions.
15039: 
15040: forth_init(imagefile)
15041: forth_evaluate(string) exceptions?
15042: forth_goto(address) (or forth_execute(xt)?)
15043: forth_continue() (a corountining mechanism)
15044: 
15045: Adding primitives.
15046: 
15047: No checking.
15048: 
15049: Signals?
15050: 
15051: Accessing the Stacks
15052: 
15053: @c ******************************************************************
15054: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
15055: @chapter Emacs and Gforth
15056: @cindex Emacs and Gforth
15057: 
15058: @cindex @file{gforth.el}
15059: @cindex @file{forth.el}
15060: @cindex Rydqvist, Goran
15061: @cindex Kuehling, David
15062: @cindex comment editing commands
15063: @cindex @code{\}, editing with Emacs
15064: @cindex debug tracer editing commands
15065: @cindex @code{~~}, removal with Emacs
15066: @cindex Forth mode in Emacs
15067: 
15068: Gforth comes with @file{gforth.el}, an improved version of
15069: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
15070: improvements are:
15071: 
15072: @itemize @bullet
15073: @item
15074: A better handling of indentation.
15075: @item
15076: A custom hilighting engine for Forth-code.
15077: @item
15078: Comment paragraph filling (@kbd{M-q})
15079: @item
15080: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
15081: @item
15082: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
15083: @item
15084: Support of the @code{info-lookup} feature for looking up the
15085: documentation of a word.
15086: @item
15087: Support for reading and writing blocks files.
15088: @end itemize
15089: 
15090: To get a basic description of these features, enter Forth mode and
15091: type @kbd{C-h m}.
15092: 
15093: @cindex source location of error or debugging output in Emacs
15094: @cindex error output, finding the source location in Emacs
15095: @cindex debugging output, finding the source location in Emacs
15096: In addition, Gforth supports Emacs quite well: The source code locations
15097: given in error messages, debugging output (from @code{~~}) and failed
15098: assertion messages are in the right format for Emacs' compilation mode
15099: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
15100: Manual}) so the source location corresponding to an error or other
15101: message is only a few keystrokes away (@kbd{C-x `} for the next error,
15102: @kbd{C-c C-c} for the error under the cursor).
15103: 
15104: @cindex viewing the documentation of a word in Emacs
15105: @cindex context-sensitive help
15106: Moreover, for words documented in this manual, you can look up the
15107: glossary entry quickly by using @kbd{C-h TAB}
15108: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
15109: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
15110: later and does not work for words containing @code{:}.
15111: 
15112: @menu
15113: * Installing gforth.el::        Making Emacs aware of Forth.
15114: * Emacs Tags::                  Viewing the source of a word in Emacs.
15115: * Hilighting::                  Making Forth code look prettier.
15116: * Auto-Indentation::            Customizing auto-indentation.
15117: * Blocks Files::                Reading and writing blocks files.
15118: @end menu
15119: 
15120: @c ----------------------------------
15121: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
15122: @section Installing gforth.el
15123: @cindex @file{.emacs}
15124: @cindex @file{gforth.el}, installation
15125: To make the features from @file{gforth.el} available in Emacs, add
15126: the following lines to your @file{.emacs} file:
15127: 
15128: @example
15129: (autoload 'forth-mode "gforth.el")
15130: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
15131: 			    auto-mode-alist))
15132: (autoload 'forth-block-mode "gforth.el")
15133: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
15134: 			    auto-mode-alist))
15135: (add-hook 'forth-mode-hook (function (lambda ()
15136:    ;; customize variables here:
15137:    (setq forth-indent-level 4)
15138:    (setq forth-minor-indent-level 2)
15139:    (setq forth-hilight-level 3)
15140:    ;;; ...
15141: )))
15142: @end example
15143: 
15144: @c ----------------------------------
15145: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
15146: @section Emacs Tags
15147: @cindex @file{TAGS} file
15148: @cindex @file{etags.fs}
15149: @cindex viewing the source of a word in Emacs
15150: @cindex @code{require}, placement in files
15151: @cindex @code{include}, placement in files
15152: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
15153: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
15154: contains the definitions of all words defined afterwards. You can then
15155: find the source for a word using @kbd{M-.}. Note that Emacs can use
15156: several tags files at the same time (e.g., one for the Gforth sources
15157: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
15158: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
15159: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
15160: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
15161: with @file{etags.fs}, you should avoid putting definitions both before
15162: and after @code{require} etc., otherwise you will see the same file
15163: visited several times by commands like @code{tags-search}.
15164: 
15165: @c ----------------------------------
15166: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
15167: @section Hilighting
15168: @cindex hilighting Forth code in Emacs
15169: @cindex highlighting Forth code in Emacs
15170: @file{gforth.el} comes with a custom source hilighting engine.  When
15171: you open a file in @code{forth-mode}, it will be completely parsed,
15172: assigning faces to keywords, comments, strings etc.  While you edit
15173: the file, modified regions get parsed and updated on-the-fly. 
15174: 
15175: Use the variable `forth-hilight-level' to change the level of
15176: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
15177: you set the hilighting level to 0, the parser will still work in the
15178: background, collecting information about whether regions of text are
15179: ``compiled'' or ``interpreted''.  Those information are required for
15180: auto-indentation to work properly.  Set `forth-disable-parser' to
15181: non-nil if your computer is too slow to handle parsing.  This will
15182: have an impact on the smartness of the auto-indentation engine,
15183: though.
15184: 
15185: Sometimes Forth sources define new features that should be hilighted,
15186: new control structures, defining-words etc.  You can use the variable
15187: `forth-custom-words' to make @code{forth-mode} hilight additional
15188: words and constructs.  See the docstring of `forth-words' for details
15189: (in Emacs, type @kbd{C-h v forth-words}).
15190: 
15191: `forth-custom-words' is meant to be customized in your
15192: @file{.emacs} file.  To customize hilighing in a file-specific manner,
15193: set `forth-local-words' in a local-variables section at the end of
15194: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
15195: 
15196: Example:
15197: @example
15198: 0 [IF]
15199:    Local Variables:
15200:    forth-local-words:
15201:       ((("t:") definition-starter (font-lock-keyword-face . 1)
15202:         "[ \t\n]" t name (font-lock-function-name-face . 3))
15203:        ((";t") definition-ender (font-lock-keyword-face . 1)))
15204:    End:
15205: [THEN]
15206: @end example
15207: 
15208: @c ----------------------------------
15209: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
15210: @section Auto-Indentation
15211: @cindex auto-indentation of Forth code in Emacs
15212: @cindex indentation of Forth code in Emacs
15213: @code{forth-mode} automatically tries to indent lines in a smart way,
15214: whenever you type @key{TAB} or break a line with @kbd{C-m}.
15215: 
15216: Simple customization can be achieved by setting
15217: `forth-indent-level' and `forth-minor-indent-level' in your
15218: @file{.emacs} file. For historical reasons @file{gforth.el} indents
15219: per default by multiples of 4 columns.  To use the more traditional
15220: 3-column indentation, add the following lines to your @file{.emacs}:
15221: 
15222: @example
15223: (add-hook 'forth-mode-hook (function (lambda ()
15224:    ;; customize variables here:
15225:    (setq forth-indent-level 3)
15226:    (setq forth-minor-indent-level 1)
15227: )))
15228: @end example
15229: 
15230: If you want indentation to recognize non-default words, customize it
15231: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
15232: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
15233: v forth-indent-words}).
15234: 
15235: To customize indentation in a file-specific manner, set
15236: `forth-local-indent-words' in a local-variables section at the end of
15237: your source file (@pxref{Local Variables in Files, Variables,,emacs,
15238: Emacs Manual}).
15239: 
15240: Example:
15241: @example
15242: 0 [IF]
15243:    Local Variables:
15244:    forth-local-indent-words:
15245:       ((("t:") (0 . 2) (0 . 2))
15246:        ((";t") (-2 . 0) (0 . -2)))
15247:    End:
15248: [THEN]
15249: @end example
15250: 
15251: @c ----------------------------------
15252: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
15253: @section Blocks Files
15254: @cindex blocks files, use with Emacs
15255: @code{forth-mode} Autodetects blocks files by checking whether the
15256: length of the first line exceeds 1023 characters.  It then tries to
15257: convert the file into normal text format.  When you save the file, it
15258: will be written to disk as normal stream-source file.
15259: 
15260: If you want to write blocks files, use @code{forth-blocks-mode}.  It
15261: inherits all the features from @code{forth-mode}, plus some additions:
15262: 
15263: @itemize @bullet
15264: @item
15265: Files are written to disk in blocks file format.
15266: @item
15267: Screen numbers are displayed in the mode line (enumerated beginning
15268: with the value of `forth-block-base')
15269: @item
15270: Warnings are displayed when lines exceed 64 characters.
15271: @item
15272: The beginning of the currently edited block is marked with an
15273: overlay-arrow. 
15274: @end itemize
15275: 
15276: There are some restrictions you should be aware of.  When you open a
15277: blocks file that contains tabulator or newline characters, these
15278: characters will be translated into spaces when the file is written
15279: back to disk.  If tabs or newlines are encountered during blocks file
15280: reading, an error is output to the echo area. So have a look at the
15281: `*Messages*' buffer, when Emacs' bell rings during reading.
15282: 
15283: Please consult the docstring of @code{forth-blocks-mode} for more
15284: information by typing @kbd{C-h v forth-blocks-mode}).
15285: 
15286: @c ******************************************************************
15287: @node Image Files, Engine, Emacs and Gforth, Top
15288: @chapter Image Files
15289: @cindex image file
15290: @cindex @file{.fi} files
15291: @cindex precompiled Forth code
15292: @cindex dictionary in persistent form
15293: @cindex persistent form of dictionary
15294: 
15295: An image file is a file containing an image of the Forth dictionary,
15296: i.e., compiled Forth code and data residing in the dictionary.  By
15297: convention, we use the extension @code{.fi} for image files.
15298: 
15299: @menu
15300: * Image Licensing Issues::      Distribution terms for images.
15301: * Image File Background::       Why have image files?
15302: * Non-Relocatable Image Files::  don't always work.
15303: * Data-Relocatable Image Files::  are better.
15304: * Fully Relocatable Image Files::  better yet.
15305: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
15306: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
15307: * Modifying the Startup Sequence::  and turnkey applications.
15308: @end menu
15309: 
15310: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15311: @section Image Licensing Issues
15312: @cindex license for images
15313: @cindex image license
15314: 
15315: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15316: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15317: original image; i.e., according to copyright law it is a derived work of
15318: the original image.
15319: 
15320: Since Gforth is distributed under the GNU GPL, the newly created image
15321: falls under the GNU GPL, too. In particular, this means that if you
15322: distribute the image, you have to make all of the sources for the image
15323: available, including those you wrote.  For details see @ref{Copying, ,
15324: GNU General Public License (Section 3)}.
15325: 
15326: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15327: contains only code compiled from the sources you gave it; if none of
15328: these sources is under the GPL, the terms discussed above do not apply
15329: to the image. However, if your image needs an engine (a gforth binary)
15330: that is under the GPL, you should make sure that you distribute both in
15331: a way that is at most a @emph{mere aggregation}, if you don't want the
15332: terms of the GPL to apply to the image.
15333: 
15334: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
15335: @section Image File Background
15336: @cindex image file background
15337: 
15338: Gforth consists not only of primitives (in the engine), but also of
15339: definitions written in Forth. Since the Forth compiler itself belongs to
15340: those definitions, it is not possible to start the system with the
15341: engine and the Forth source alone. Therefore we provide the Forth
15342: code as an image file in nearly executable form. When Gforth starts up,
15343: a C routine loads the image file into memory, optionally relocates the
15344: addresses, then sets up the memory (stacks etc.) according to
15345: information in the image file, and (finally) starts executing Forth
15346: code.
15347: 
15348: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
15349: You can use a different image by using the @code{-i},
15350: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
15351: Gforth}), e.g.:
15352: 
15353: @example
15354: gforth-fast -i myimage.fi
15355: @end example
15356: 
15357: There are different variants of image files, and they represent
15358: different compromises between the goals of making it easy to generate
15359: image files and making them portable.
15360: 
15361: @cindex relocation at run-time
15362: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
15363: run-time. This avoids many of the complications discussed below (image
15364: files are data relocatable without further ado), but costs performance
15365: (one addition per memory access) and makes it difficult to pass
15366: addresses between Forth and library calls or other programs.
15367: 
15368: @cindex relocation at load-time
15369: By contrast, the Gforth loader performs relocation at image load time. The
15370: loader also has to replace tokens that represent primitive calls with the
15371: appropriate code-field addresses (or code addresses in the case of
15372: direct threading).
15373: 
15374: There are three kinds of image files, with different degrees of
15375: relocatability: non-relocatable, data-relocatable, and fully relocatable
15376: image files.
15377: 
15378: @cindex image file loader
15379: @cindex relocating loader
15380: @cindex loader for image files
15381: These image file variants have several restrictions in common; they are
15382: caused by the design of the image file loader:
15383: 
15384: @itemize @bullet
15385: @item
15386: There is only one segment; in particular, this means, that an image file
15387: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
15388: them). The contents of the stacks are not represented, either.
15389: 
15390: @item
15391: The only kinds of relocation supported are: adding the same offset to
15392: all cells that represent data addresses; and replacing special tokens
15393: with code addresses or with pieces of machine code.
15394: 
15395: If any complex computations involving addresses are performed, the
15396: results cannot be represented in the image file. Several applications that
15397: use such computations come to mind:
15398: 
15399: @itemize @minus
15400: @item
15401: Hashing addresses (or data structures which contain addresses) for table
15402: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15403: purpose, you will have no problem, because the hash tables are
15404: recomputed automatically when the system is started. If you use your own
15405: hash tables, you will have to do something similar.
15406: 
15407: @item
15408: There's a cute implementation of doubly-linked lists that uses
15409: @code{XOR}ed addresses. You could represent such lists as singly-linked
15410: in the image file, and restore the doubly-linked representation on
15411: startup.@footnote{In my opinion, though, you should think thrice before
15412: using a doubly-linked list (whatever implementation).}
15413: 
15414: @item
15415: The code addresses of run-time routines like @code{docol:} cannot be
15416: represented in the image file (because their tokens would be replaced by
15417: machine code in direct threaded implementations). As a workaround,
15418: compute these addresses at run-time with @code{>code-address} from the
15419: executions tokens of appropriate words (see the definitions of
15420: @code{docol:} and friends in @file{kernel/getdoers.fs}).
15421: 
15422: @item
15423: On many architectures addresses are represented in machine code in some
15424: shifted or mangled form. You cannot put @code{CODE} words that contain
15425: absolute addresses in this form in a relocatable image file. Workarounds
15426: are representing the address in some relative form (e.g., relative to
15427: the CFA, which is present in some register), or loading the address from
15428: a place where it is stored in a non-mangled form.
15429: @end itemize
15430: @end itemize
15431: 
15432: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15433: @section Non-Relocatable Image Files
15434: @cindex non-relocatable image files
15435: @cindex image file, non-relocatable
15436: 
15437: These files are simple memory dumps of the dictionary. They are
15438: specific to the executable (i.e., @file{gforth} file) they were
15439: created with. What's worse, they are specific to the place on which
15440: the dictionary resided when the image was created. Now, there is no
15441: guarantee that the dictionary will reside at the same place the next
15442: time you start Gforth, so there's no guarantee that a non-relocatable
15443: image will work the next time (Gforth will complain instead of
15444: crashing, though).  Indeed, on OSs with (enabled) address-space
15445: randomization non-relocatable images are unlikely to work.
15446: 
15447: You can create a non-relocatable image file with @code{savesystem}, e.g.:
15448: 
15449: @example
15450: gforth app.fs -e "savesystem app.fi bye"
15451: @end example
15452: 
15453: doc-savesystem
15454: 
15455: 
15456: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15457: @section Data-Relocatable Image Files
15458: @cindex data-relocatable image files
15459: @cindex image file, data-relocatable
15460: 
15461: These files contain relocatable data addresses, but fixed code
15462: addresses (instead of tokens). They are specific to the executable
15463: (i.e., @file{gforth} file) they were created with.  Also, they disable
15464: dynamic native code generation (typically a factor of 2 in speed).
15465: You get a data-relocatable image, if you pass the engine you want to
15466: use through the @code{GFORTHD} environment variable to @file{gforthmi}
15467: (@pxref{gforthmi}), e.g.
15468: 
15469: @example
15470: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
15471: @end example
15472: 
15473: Note that the @code{--no-dynamic} is required here for the image to
15474: work (otherwise it will contain references to dynamically generated
15475: code that is not saved in the image).
15476: 
15477: 
15478: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15479: @section Fully Relocatable Image Files
15480: @cindex fully relocatable image files
15481: @cindex image file, fully relocatable
15482: 
15483: @cindex @file{kern*.fi}, relocatability
15484: @cindex @file{gforth.fi}, relocatability
15485: These image files have relocatable data addresses, and tokens for code
15486: addresses. They can be used with different binaries (e.g., with and
15487: without debugging) on the same machine, and even across machines with
15488: the same data formats (byte order, cell size, floating point format),
15489: and they work with dynamic native code generation.  However, they are
15490: usually specific to the version of Gforth they were created with. The
15491: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
15492: 
15493: There are two ways to create a fully relocatable image file:
15494: 
15495: @menu
15496: * gforthmi::                    The normal way
15497: * cross.fs::                    The hard way
15498: @end menu
15499: 
15500: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15501: @subsection @file{gforthmi}
15502: @cindex @file{comp-i.fs}
15503: @cindex @file{gforthmi}
15504: 
15505: You will usually use @file{gforthmi}. If you want to create an
15506: image @i{file} that contains everything you would load by invoking
15507: Gforth with @code{gforth @i{options}}, you simply say:
15508: @example
15509: gforthmi @i{file} @i{options}
15510: @end example
15511: 
15512: E.g., if you want to create an image @file{asm.fi} that has the file
15513: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15514: like this:
15515: 
15516: @example
15517: gforthmi asm.fi asm.fs
15518: @end example
15519: 
15520: @file{gforthmi} is implemented as a sh script and works like this: It
15521: produces two non-relocatable images for different addresses and then
15522: compares them. Its output reflects this: first you see the output (if
15523: any) of the two Gforth invocations that produce the non-relocatable image
15524: files, then you see the output of the comparing program: It displays the
15525: offset used for data addresses and the offset used for code addresses;
15526: moreover, for each cell that cannot be represented correctly in the
15527: image files, it displays a line like this:
15528: 
15529: @example
15530:      78DC         BFFFFA50         BFFFFA40
15531: @end example
15532: 
15533: This means that at offset $78dc from @code{forthstart}, one input image
15534: contains $bffffa50, and the other contains $bffffa40. Since these cells
15535: cannot be represented correctly in the output image, you should examine
15536: these places in the dictionary and verify that these cells are dead
15537: (i.e., not read before they are written).
15538: 
15539: @cindex --application, @code{gforthmi} option
15540: If you insert the option @code{--application} in front of the image file
15541: name, you will get an image that uses the @code{--appl-image} option
15542: instead of the @code{--image-file} option (@pxref{Invoking
15543: Gforth}). When you execute such an image on Unix (by typing the image
15544: name as command), the Gforth engine will pass all options to the image
15545: instead of trying to interpret them as engine options.
15546: 
15547: If you type @file{gforthmi} with no arguments, it prints some usage
15548: instructions.
15549: 
15550: @cindex @code{savesystem} during @file{gforthmi}
15551: @cindex @code{bye} during @file{gforthmi}
15552: @cindex doubly indirect threaded code
15553: @cindex environment variables
15554: @cindex @code{GFORTHD} -- environment variable
15555: @cindex @code{GFORTH} -- environment variable
15556: @cindex @code{gforth-ditc}
15557: There are a few wrinkles: After processing the passed @i{options}, the
15558: words @code{savesystem} and @code{bye} must be visible. A special
15559: doubly indirect threaded version of the @file{gforth} executable is
15560: used for creating the non-relocatable images; you can pass the exact
15561: filename of this executable through the environment variable
15562: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
15563: that is not doubly indirect threaded, you will not get a fully
15564: relocatable image, but a data-relocatable image
15565: (@pxref{Data-Relocatable Image Files}), because there is no code
15566: address offset). The normal @file{gforth} executable is used for
15567: creating the relocatable image; you can pass the exact filename of
15568: this executable through the environment variable @code{GFORTH}.
15569: 
15570: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
15571: @subsection @file{cross.fs}
15572: @cindex @file{cross.fs}
15573: @cindex cross-compiler
15574: @cindex metacompiler
15575: @cindex target compiler
15576: 
15577: You can also use @code{cross}, a batch compiler that accepts a Forth-like
15578: programming language (@pxref{Cross Compiler}).
15579: 
15580: @code{cross} allows you to create image files for machines with
15581: different data sizes and data formats than the one used for generating
15582: the image file. You can also use it to create an application image that
15583: does not contain a Forth compiler. These features are bought with
15584: restrictions and inconveniences in programming. E.g., addresses have to
15585: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15586: order to make the code relocatable.
15587: 
15588: 
15589: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15590: @section Stack and Dictionary Sizes
15591: @cindex image file, stack and dictionary sizes
15592: @cindex dictionary size default
15593: @cindex stack size default
15594: 
15595: If you invoke Gforth with a command line flag for the size
15596: (@pxref{Invoking Gforth}), the size you specify is stored in the
15597: dictionary. If you save the dictionary with @code{savesystem} or create
15598: an image with @file{gforthmi}, this size will become the default
15599: for the resulting image file. E.g., the following will create a
15600: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
15601: 
15602: @example
15603: gforthmi gforth.fi -m 1M
15604: @end example
15605: 
15606: In other words, if you want to set the default size for the dictionary
15607: and the stacks of an image, just invoke @file{gforthmi} with the
15608: appropriate options when creating the image.
15609: 
15610: @cindex stack size, cache-friendly
15611: Note: For cache-friendly behaviour (i.e., good performance), you should
15612: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15613: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15614: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15615: 
15616: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15617: @section Running Image Files
15618: @cindex running image files
15619: @cindex invoking image files
15620: @cindex image file invocation
15621: 
15622: @cindex -i, invoke image file
15623: @cindex --image file, invoke image file
15624: You can invoke Gforth with an image file @i{image} instead of the
15625: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15626: @example
15627: gforth -i @i{image}
15628: @end example
15629: 
15630: @cindex executable image file
15631: @cindex image file, executable
15632: If your operating system supports starting scripts with a line of the
15633: form @code{#! ...}, you just have to type the image file name to start
15634: Gforth with this image file (note that the file extension @code{.fi} is
15635: just a convention). I.e., to run Gforth with the image file @i{image},
15636: you can just type @i{image} instead of @code{gforth -i @i{image}}.
15637: This works because every @code{.fi} file starts with a line of this
15638: format:
15639: 
15640: @example
15641: #! /usr/local/bin/gforth-0.4.0 -i
15642: @end example
15643: 
15644: The file and pathname for the Gforth engine specified on this line is
15645: the specific Gforth executable that it was built against; i.e. the value
15646: of the environment variable @code{GFORTH} at the time that
15647: @file{gforthmi} was executed.
15648: 
15649: You can make use of the same shell capability to make a Forth source
15650: file into an executable. For example, if you place this text in a file:
15651: 
15652: @example
15653: #! /usr/local/bin/gforth
15654: 
15655: ." Hello, world" CR
15656: bye
15657: @end example
15658: 
15659: @noindent
15660: and then make the file executable (chmod +x in Unix), you can run it
15661: directly from the command line. The sequence @code{#!} is used in two
15662: ways; firstly, it is recognised as a ``magic sequence'' by the operating
15663: system@footnote{The Unix kernel actually recognises two types of files:
15664: executable files and files of data, where the data is processed by an
15665: interpreter that is specified on the ``interpreter line'' -- the first
15666: line of the file, starting with the sequence #!. There may be a small
15667: limit (e.g., 32) on the number of characters that may be specified on
15668: the interpreter line.} secondly it is treated as a comment character by
15669: Gforth. Because of the second usage, a space is required between
15670: @code{#!} and the path to the executable (moreover, some Unixes
15671: require the sequence @code{#! /}).
15672: 
15673: The disadvantage of this latter technique, compared with using
15674: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15675: compiled on-the-fly, each time the program is invoked.
15676: 
15677: doc-#!
15678: 
15679: 
15680: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
15681: @section Modifying the Startup Sequence
15682: @cindex startup sequence for image file
15683: @cindex image file initialization sequence
15684: @cindex initialization sequence of image file
15685: 
15686: You can add your own initialization to the startup sequence of an image
15687: through the deferred word @code{'cold}. @code{'cold} is invoked just
15688: before the image-specific command line processing (i.e., loading files
15689: and evaluating (@code{-e}) strings) starts.
15690: 
15691: A sequence for adding your initialization usually looks like this:
15692: 
15693: @example
15694: :noname
15695:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15696:     ... \ your stuff
15697: ; IS 'cold
15698: @end example
15699: 
15700: After @code{'cold}, Gforth processes the image options
15701: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15702: another deferred word.  This normally prints Gforth's startup message
15703: and does nothing else.
15704: 
15705: @cindex turnkey image files
15706: @cindex image file, turnkey applications
15707: So, if you want to make a turnkey image (i.e., an image for an
15708: application instead of an extended Forth system), you can do this in
15709: two ways:
15710: 
15711: @itemize @bullet
15712: 
15713: @item
15714: If you want to do your interpretation of the OS command-line
15715: arguments, hook into @code{'cold}.  In that case you probably also
15716: want to build the image with @code{gforthmi --application}
15717: (@pxref{gforthmi}) to keep the engine from processing OS command line
15718: options.  You can then do your own command-line processing with
15719: @code{next-arg} 
15720: 
15721: @item
15722: If you want to have the normal Gforth processing of OS command-line
15723: arguments, hook into @code{bootmessage}.
15724: 
15725: @end itemize
15726: 
15727: In either case, you probably do not want the word that you execute in
15728: these hooks to exit normally, but use @code{bye} or @code{throw}.
15729: Otherwise the Gforth startup process would continue and eventually
15730: present the Forth command line to the user.
15731: 
15732: doc-'cold
15733: doc-bootmessage
15734: 
15735: @c ******************************************************************
15736: @node Engine, Cross Compiler, Image Files, Top
15737: @chapter Engine
15738: @cindex engine
15739: @cindex virtual machine
15740: 
15741: Reading this chapter is not necessary for programming with Gforth. It
15742: may be helpful for finding your way in the Gforth sources.
15743: 
15744: The ideas in this section have also been published in the following
15745: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15746: Forth-Tagung '93; M. Anton Ertl,
15747: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15748: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15749: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15750: Threaded code variations and optimizations (extended version)}},
15751: Forth-Tagung '02.
15752: 
15753: @menu
15754: * Portability::                 
15755: * Threading::                   
15756: * Primitives::                  
15757: * Performance::                 
15758: @end menu
15759: 
15760: @node Portability, Threading, Engine, Engine
15761: @section Portability
15762: @cindex engine portability
15763: 
15764: An important goal of the Gforth Project is availability across a wide
15765: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15766: achieved this goal by manually coding the engine in assembly language
15767: for several then-popular processors. This approach is very
15768: labor-intensive and the results are short-lived due to progress in
15769: computer architecture.
15770: 
15771: @cindex C, using C for the engine
15772: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15773: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15774: particularly popular for UNIX-based Forths due to the large variety of
15775: architectures of UNIX machines. Unfortunately an implementation in C
15776: does not mix well with the goals of efficiency and with using
15777: traditional techniques: Indirect or direct threading cannot be expressed
15778: in C, and switch threading, the fastest technique available in C, is
15779: significantly slower. Another problem with C is that it is very
15780: cumbersome to express double integer arithmetic.
15781: 
15782: @cindex GNU C for the engine
15783: @cindex long long
15784: Fortunately, there is a portable language that does not have these
15785: limitations: GNU C, the version of C processed by the GNU C compiler
15786: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15787: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15788: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15789: threading possible, its @code{long long} type (@pxref{Long Long, ,
15790: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
15791: double numbers on many systems.  GNU C is freely available on all
15792: important (and many unimportant) UNIX machines, VMS, 80386s running
15793: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15794: on all these machines.
15795: 
15796: Writing in a portable language has the reputation of producing code that
15797: is slower than assembly. For our Forth engine we repeatedly looked at
15798: the code produced by the compiler and eliminated most compiler-induced
15799: inefficiencies by appropriate changes in the source code.
15800: 
15801: @cindex explicit register declarations
15802: @cindex --enable-force-reg, configuration flag
15803: @cindex -DFORCE_REG
15804: However, register allocation cannot be portably influenced by the
15805: programmer, leading to some inefficiencies on register-starved
15806: machines. We use explicit register declarations (@pxref{Explicit Reg
15807: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15808: improve the speed on some machines. They are turned on by using the
15809: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15810: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15811: machine, but also on the compiler version: On some machines some
15812: compiler versions produce incorrect code when certain explicit register
15813: declarations are used. So by default @code{-DFORCE_REG} is not used.
15814: 
15815: @node Threading, Primitives, Portability, Engine
15816: @section Threading
15817: @cindex inner interpreter implementation
15818: @cindex threaded code implementation
15819: 
15820: @cindex labels as values
15821: GNU C's labels as values extension (available since @code{gcc-2.0},
15822: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
15823: makes it possible to take the address of @i{label} by writing
15824: @code{&&@i{label}}.  This address can then be used in a statement like
15825: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
15826: @code{goto x}.
15827: 
15828: @cindex @code{NEXT}, indirect threaded
15829: @cindex indirect threaded inner interpreter
15830: @cindex inner interpreter, indirect threaded
15831: With this feature an indirect threaded @code{NEXT} looks like:
15832: @example
15833: cfa = *ip++;
15834: ca = *cfa;
15835: goto *ca;
15836: @end example
15837: @cindex instruction pointer
15838: For those unfamiliar with the names: @code{ip} is the Forth instruction
15839: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15840: execution token and points to the code field of the next word to be
15841: executed; The @code{ca} (code address) fetched from there points to some
15842: executable code, e.g., a primitive or the colon definition handler
15843: @code{docol}.
15844: 
15845: @cindex @code{NEXT}, direct threaded
15846: @cindex direct threaded inner interpreter
15847: @cindex inner interpreter, direct threaded
15848: Direct threading is even simpler:
15849: @example
15850: ca = *ip++;
15851: goto *ca;
15852: @end example
15853: 
15854: Of course we have packaged the whole thing neatly in macros called
15855: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
15856: 
15857: @menu
15858: * Scheduling::                  
15859: * Direct or Indirect Threaded?::  
15860: * Dynamic Superinstructions::   
15861: * DOES>::                       
15862: @end menu
15863: 
15864: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15865: @subsection Scheduling
15866: @cindex inner interpreter optimization
15867: 
15868: There is a little complication: Pipelined and superscalar processors,
15869: i.e., RISC and some modern CISC machines can process independent
15870: instructions while waiting for the results of an instruction. The
15871: compiler usually reorders (schedules) the instructions in a way that
15872: achieves good usage of these delay slots. However, on our first tries
15873: the compiler did not do well on scheduling primitives. E.g., for
15874: @code{+} implemented as
15875: @example
15876: n=sp[0]+sp[1];
15877: sp++;
15878: sp[0]=n;
15879: NEXT;
15880: @end example
15881: the @code{NEXT} comes strictly after the other code, i.e., there is
15882: nearly no scheduling. After a little thought the problem becomes clear:
15883: The compiler cannot know that @code{sp} and @code{ip} point to different
15884: addresses (and the version of @code{gcc} we used would not know it even
15885: if it was possible), so it could not move the load of the cfa above the
15886: store to the TOS. Indeed the pointers could be the same, if code on or
15887: very near the top of stack were executed. In the interest of speed we
15888: chose to forbid this probably unused ``feature'' and helped the compiler
15889: in scheduling: @code{NEXT} is divided into several parts:
15890: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15891: like:
15892: @example
15893: NEXT_P0;
15894: n=sp[0]+sp[1];
15895: sp++;
15896: NEXT_P1;
15897: sp[0]=n;
15898: NEXT_P2;
15899: @end example
15900: 
15901: There are various schemes that distribute the different operations of
15902: NEXT between these parts in several ways; in general, different schemes
15903: perform best on different processors.  We use a scheme for most
15904: architectures that performs well for most processors of this
15905: architecture; in the future we may switch to benchmarking and chosing
15906: the scheme on installation time.
15907: 
15908: 
15909: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
15910: @subsection Direct or Indirect Threaded?
15911: @cindex threading, direct or indirect?
15912: 
15913: Threaded forth code consists of references to primitives (simple machine
15914: code routines like @code{+}) and to non-primitives (e.g., colon
15915: definitions, variables, constants); for a specific class of
15916: non-primitives (e.g., variables) there is one code routine (e.g.,
15917: @code{dovar}), but each variable needs a separate reference to its data.
15918: 
15919: Traditionally Forth has been implemented as indirect threaded code,
15920: because this allows to use only one cell to reference a non-primitive
15921: (basically you point to the data, and find the code address there).
15922: 
15923: @cindex primitive-centric threaded code
15924: However, threaded code in Gforth (since 0.6.0) uses two cells for
15925: non-primitives, one for the code address, and one for the data address;
15926: the data pointer is an immediate argument for the virtual machine
15927: instruction represented by the code address.  We call this
15928: @emph{primitive-centric} threaded code, because all code addresses point
15929: to simple primitives.  E.g., for a variable, the code address is for
15930: @code{lit} (also used for integer literals like @code{99}).
15931: 
15932: Primitive-centric threaded code allows us to use (faster) direct
15933: threading as dispatch method, completely portably (direct threaded code
15934: in Gforth before 0.6.0 required architecture-specific code).  It also
15935: eliminates the performance problems related to I-cache consistency that
15936: 386 implementations have with direct threaded code, and allows
15937: additional optimizations.
15938: 
15939: @cindex hybrid direct/indirect threaded code
15940: There is a catch, however: the @var{xt} parameter of @code{execute} can
15941: occupy only one cell, so how do we pass non-primitives with their code
15942: @emph{and} data addresses to them?  Our answer is to use indirect
15943: threaded dispatch for @code{execute} and other words that use a
15944: single-cell xt.  So, normal threaded code in colon definitions uses
15945: direct threading, and @code{execute} and similar words, which dispatch
15946: to xts on the data stack, use indirect threaded code.  We call this
15947: @emph{hybrid direct/indirect} threaded code.
15948: 
15949: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15950: @cindex gforth engine
15951: @cindex gforth-fast engine
15952: The engines @command{gforth} and @command{gforth-fast} use hybrid
15953: direct/indirect threaded code.  This means that with these engines you
15954: cannot use @code{,} to compile an xt.  Instead, you have to use
15955: @code{compile,}.
15956: 
15957: @cindex gforth-itc engine
15958: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15959: This engine uses plain old indirect threaded code.  It still compiles in
15960: a primitive-centric style, so you cannot use @code{compile,} instead of
15961: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
15962: ... [}).  If you want to do that, you have to use @command{gforth-itc}
15963: and execute @code{' , is compile,}.  Your program can check if it is
15964: running on a hybrid direct/indirect threaded engine or a pure indirect
15965: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15966: 
15967: 
15968: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15969: @subsection Dynamic Superinstructions
15970: @cindex Dynamic superinstructions with replication
15971: @cindex Superinstructions
15972: @cindex Replication
15973: 
15974: The engines @command{gforth} and @command{gforth-fast} use another
15975: optimization: Dynamic superinstructions with replication.  As an
15976: example, consider the following colon definition:
15977: 
15978: @example
15979: : squared ( n1 -- n2 )
15980:   dup * ;
15981: @end example
15982: 
15983: Gforth compiles this into the threaded code sequence
15984: 
15985: @example
15986: dup
15987: *
15988: ;s
15989: @end example
15990: 
15991: In normal direct threaded code there is a code address occupying one
15992: cell for each of these primitives.  Each code address points to a
15993: machine code routine, and the interpreter jumps to this machine code in
15994: order to execute the primitive.  The routines for these three
15995: primitives are (in @command{gforth-fast} on the 386):
15996: 
15997: @example
15998: Code dup  
15999: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
16000: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
16001: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
16002: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
16003: end-code
16004: Code *  
16005: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
16006: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
16007: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
16008: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
16009: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
16010: end-code
16011: Code ;s  
16012: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
16013: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
16014: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
16015: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
16016: end-code
16017: @end example
16018: 
16019: With dynamic superinstructions and replication the compiler does not
16020: just lay down the threaded code, but also copies the machine code
16021: fragments, usually without the jump at the end.
16022: 
16023: @example
16024: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
16025: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
16026: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
16027: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
16028: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
16029: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
16030: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
16031: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
16032: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
16033: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
16034: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
16035: @end example
16036: 
16037: Only when a threaded-code control-flow change happens (e.g., in
16038: @code{;s}), the jump is appended.  This optimization eliminates many of
16039: these jumps and makes the rest much more predictable.  The speedup
16040: depends on the processor and the application; on the Athlon and Pentium
16041: III this optimization typically produces a speedup by a factor of 2.
16042: 
16043: The code addresses in the direct-threaded code are set to point to the
16044: appropriate points in the copied machine code, in this example like
16045: this:
16046: 
16047: @example
16048: primitive  code address
16049:    dup       $4057D27D
16050:    *         $4057D286
16051:    ;s        $4057D292
16052: @end example
16053: 
16054: Thus there can be threaded-code jumps to any place in this piece of
16055: code.  This also simplifies decompilation quite a bit.
16056: 
16057: @cindex --no-dynamic command-line option
16058: @cindex --no-super command-line option
16059: You can disable this optimization with @option{--no-dynamic}.  You can
16060: use the copying without eliminating the jumps (i.e., dynamic
16061: replication, but without superinstructions) with @option{--no-super};
16062: this gives the branch prediction benefit alone; the effect on
16063: performance depends on the CPU; on the Athlon and Pentium III the
16064: speedup is a little less than for dynamic superinstructions with
16065: replication.
16066: 
16067: @cindex patching threaded code
16068: One use of these options is if you want to patch the threaded code.
16069: With superinstructions, many of the dispatch jumps are eliminated, so
16070: patching often has no effect.  These options preserve all the dispatch
16071: jumps.
16072: 
16073: @cindex --dynamic command-line option
16074: On some machines dynamic superinstructions are disabled by default,
16075: because it is unsafe on these machines.  However, if you feel
16076: adventurous, you can enable it with @option{--dynamic}.
16077: 
16078: @node DOES>,  , Dynamic Superinstructions, Threading
16079: @subsection DOES>
16080: @cindex @code{DOES>} implementation
16081: 
16082: @cindex @code{dodoes} routine
16083: @cindex @code{DOES>}-code
16084: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
16085: the chunk of code executed by every word defined by a
16086: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
16087: this is only needed if the xt of the word is @code{execute}d. The main
16088: problem here is: How to find the Forth code to be executed, i.e. the
16089: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
16090: solutions:
16091: 
16092: In fig-Forth the code field points directly to the @code{dodoes} and the
16093: @code{DOES>}-code address is stored in the cell after the code address
16094: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
16095: illegal in the Forth-79 and all later standards, because in fig-Forth
16096: this address lies in the body (which is illegal in these
16097: standards). However, by making the code field larger for all words this
16098: solution becomes legal again.  We use this approach.  Leaving a cell
16099: unused in most words is a bit wasteful, but on the machines we are
16100: targeting this is hardly a problem.
16101: 
16102: 
16103: @node Primitives, Performance, Threading, Engine
16104: @section Primitives
16105: @cindex primitives, implementation
16106: @cindex virtual machine instructions, implementation
16107: 
16108: @menu
16109: * Automatic Generation::        
16110: * TOS Optimization::            
16111: * Produced code::               
16112: @end menu
16113: 
16114: @node Automatic Generation, TOS Optimization, Primitives, Primitives
16115: @subsection Automatic Generation
16116: @cindex primitives, automatic generation
16117: 
16118: @cindex @file{prims2x.fs}
16119: 
16120: Since the primitives are implemented in a portable language, there is no
16121: longer any need to minimize the number of primitives. On the contrary,
16122: having many primitives has an advantage: speed. In order to reduce the
16123: number of errors in primitives and to make programming them easier, we
16124: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
16125: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
16126: generates most (and sometimes all) of the C code for a primitive from
16127: the stack effect notation.  The source for a primitive has the following
16128: form:
16129: 
16130: @cindex primitive source format
16131: @format
16132: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
16133: [@code{""}@i{glossary entry}@code{""}]
16134: @i{C code}
16135: [@code{:}
16136: @i{Forth code}]
16137: @end format
16138: 
16139: The items in brackets are optional. The category and glossary fields
16140: are there for generating the documentation, the Forth code is there
16141: for manual implementations on machines without GNU C. E.g., the source
16142: for the primitive @code{+} is:
16143: @example
16144: +    ( n1 n2 -- n )   core    plus
16145: n = n1+n2;
16146: @end example
16147: 
16148: This looks like a specification, but in fact @code{n = n1+n2} is C
16149: code. Our primitive generation tool extracts a lot of information from
16150: the stack effect notations@footnote{We use a one-stack notation, even
16151: though we have separate data and floating-point stacks; The separate
16152: notation can be generated easily from the unified notation.}: The number
16153: of items popped from and pushed on the stack, their type, and by what
16154: name they are referred to in the C code. It then generates a C code
16155: prelude and postlude for each primitive. The final C code for @code{+}
16156: looks like this:
16157: 
16158: @example
16159: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
16160: /*  */                          /* documentation */
16161: NAME("+")                       /* debugging output (with -DDEBUG) */
16162: @{
16163: DEF_CA                          /* definition of variable ca (indirect threading) */
16164: Cell n1;                        /* definitions of variables */
16165: Cell n2;
16166: Cell n;
16167: NEXT_P0;                        /* NEXT part 0 */
16168: n1 = (Cell) sp[1];              /* input */
16169: n2 = (Cell) TOS;
16170: sp += 1;                        /* stack adjustment */
16171: @{
16172: n = n1+n2;                      /* C code taken from the source */
16173: @}
16174: NEXT_P1;                        /* NEXT part 1 */
16175: TOS = (Cell)n;                  /* output */
16176: NEXT_P2;                        /* NEXT part 2 */
16177: @}
16178: @end example
16179: 
16180: This looks long and inefficient, but the GNU C compiler optimizes quite
16181: well and produces optimal code for @code{+} on, e.g., the R3000 and the
16182: HP RISC machines: Defining the @code{n}s does not produce any code, and
16183: using them as intermediate storage also adds no cost.
16184: 
16185: There are also other optimizations that are not illustrated by this
16186: example: assignments between simple variables are usually for free (copy
16187: propagation). If one of the stack items is not used by the primitive
16188: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
16189: (dead code elimination). On the other hand, there are some things that
16190: the compiler does not do, therefore they are performed by
16191: @file{prims2x.fs}: The compiler does not optimize code away that stores
16192: a stack item to the place where it just came from (e.g., @code{over}).
16193: 
16194: While programming a primitive is usually easy, there are a few cases
16195: where the programmer has to take the actions of the generator into
16196: account, most notably @code{?dup}, but also words that do not (always)
16197: fall through to @code{NEXT}.
16198: 
16199: For more information
16200: 
16201: @node TOS Optimization, Produced code, Automatic Generation, Primitives
16202: @subsection TOS Optimization
16203: @cindex TOS optimization for primitives
16204: @cindex primitives, keeping the TOS in a register
16205: 
16206: An important optimization for stack machine emulators, e.g., Forth
16207: engines, is keeping  one or more of the top stack items in
16208: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
16209: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
16210: @itemize @bullet
16211: @item
16212: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
16213: due to fewer loads from and stores to the stack.
16214: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
16215: @i{y<n}, due to additional moves between registers.
16216: @end itemize
16217: 
16218: @cindex -DUSE_TOS
16219: @cindex -DUSE_NO_TOS
16220: In particular, keeping one item in a register is never a disadvantage,
16221: if there are enough registers. Keeping two items in registers is a
16222: disadvantage for frequent words like @code{?branch}, constants,
16223: variables, literals and @code{i}. Therefore our generator only produces
16224: code that keeps zero or one items in registers. The generated C code
16225: covers both cases; the selection between these alternatives is made at
16226: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
16227: code for @code{+} is just a simple variable name in the one-item case,
16228: otherwise it is a macro that expands into @code{sp[0]}. Note that the
16229: GNU C compiler tries to keep simple variables like @code{TOS} in
16230: registers, and it usually succeeds, if there are enough registers.
16231: 
16232: @cindex -DUSE_FTOS
16233: @cindex -DUSE_NO_FTOS
16234: The primitive generator performs the TOS optimization for the
16235: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
16236: operations the benefit of this optimization is even larger:
16237: floating-point operations take quite long on most processors, but can be
16238: performed in parallel with other operations as long as their results are
16239: not used. If the FP-TOS is kept in a register, this works. If
16240: it is kept on the stack, i.e., in memory, the store into memory has to
16241: wait for the result of the floating-point operation, lengthening the
16242: execution time of the primitive considerably.
16243: 
16244: The TOS optimization makes the automatic generation of primitives a
16245: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
16246: @code{TOS} is not sufficient. There are some special cases to
16247: consider:
16248: @itemize @bullet
16249: @item In the case of @code{dup ( w -- w w )} the generator must not
16250: eliminate the store to the original location of the item on the stack,
16251: if the TOS optimization is turned on.
16252: @item Primitives with stack effects of the form @code{--}
16253: @i{out1}...@i{outy} must store the TOS to the stack at the start.
16254: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
16255: must load the TOS from the stack at the end. But for the null stack
16256: effect @code{--} no stores or loads should be generated.
16257: @end itemize
16258: 
16259: @node Produced code,  , TOS Optimization, Primitives
16260: @subsection Produced code
16261: @cindex primitives, assembly code listing
16262: 
16263: @cindex @file{engine.s}
16264: To see what assembly code is produced for the primitives on your machine
16265: with your compiler and your flag settings, type @code{make engine.s} and
16266: look at the resulting file @file{engine.s}.  Alternatively, you can also
16267: disassemble the code of primitives with @code{see} on some architectures.
16268: 
16269: @node  Performance,  , Primitives, Engine
16270: @section Performance
16271: @cindex performance of some Forth interpreters
16272: @cindex engine performance
16273: @cindex benchmarking Forth systems
16274: @cindex Gforth performance
16275: 
16276: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
16277: impossible to write a significantly faster threaded-code engine.
16278: 
16279: On register-starved machines like the 386 architecture processors
16280: improvements are possible, because @code{gcc} does not utilize the
16281: registers as well as a human, even with explicit register declarations;
16282: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16283: and hand-tuned it for the 486; this system is 1.19 times faster on the
16284: Sieve benchmark on a 486DX2/66 than Gforth compiled with
16285: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
16286: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16287: registers fit in real registers (and we can even afford to use the TOS
16288: optimization), resulting in a speedup of 1.14 on the sieve over the
16289: earlier results.  And dynamic superinstructions provide another speedup
16290: (but only around a factor 1.2 on the 486).
16291: 
16292: @cindex Win32Forth performance
16293: @cindex NT Forth performance
16294: @cindex eforth performance
16295: @cindex ThisForth performance
16296: @cindex PFE performance
16297: @cindex TILE performance
16298: The potential advantage of assembly language implementations is not
16299: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
16300: (direct threaded, compiled with @code{gcc-2.95.1} and
16301: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16302: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16303: (with and without peephole (aka pinhole) optimization of the threaded
16304: code); all these systems were written in assembly language. We also
16305: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16306: with @code{gcc-2.6.3} with the default configuration for Linux:
16307: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16308: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16309: employs peephole optimization of the threaded code) and TILE (compiled
16310: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16311: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16312: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16313: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16314: then extended it to run the benchmarks, added the peephole optimizer,
16315: ran the benchmarks and reported the results.
16316: 
16317: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16318: matrix multiplication come from the Stanford integer benchmarks and have
16319: been translated into Forth by Martin Fraeman; we used the versions
16320: included in the TILE Forth package, but with bigger data set sizes; and
16321: a recursive Fibonacci number computation for benchmarking calling
16322: performance. The following table shows the time taken for the benchmarks
16323: scaled by the time taken by Gforth (in other words, it shows the speedup
16324: factor that Gforth achieved over the other systems).
16325: 
16326: @example
16327: relative       Win32-    NT       eforth       This-      
16328: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
16329: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
16330: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
16331: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
16332: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
16333: @end example
16334: 
16335: You may be quite surprised by the good performance of Gforth when
16336: compared with systems written in assembly language. One important reason
16337: for the disappointing performance of these other systems is probably
16338: that they are not written optimally for the 486 (e.g., they use the
16339: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16340: but costly method for relocating the Forth image: like @code{cforth}, it
16341: computes the actual addresses at run time, resulting in two address
16342: computations per @code{NEXT} (@pxref{Image File Background}).
16343: 
16344: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16345: explained with the self-imposed restriction of the latter systems to
16346: standard C, which makes efficient threading impossible (however, the
16347: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
16348: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16349: Moreover, current C compilers have a hard time optimizing other aspects
16350: of the ThisForth and the TILE source.
16351: 
16352: The performance of Gforth on 386 architecture processors varies widely
16353: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16354: allocate any of the virtual machine registers into real machine
16355: registers by itself and would not work correctly with explicit register
16356: declarations, giving a significantly slower engine (on a 486DX2/66
16357: running the Sieve) than the one measured above.
16358: 
16359: Note that there have been several releases of Win32Forth since the
16360: release presented here, so the results presented above may have little
16361: predictive value for the performance of Win32Forth today (results for
16362: the current release on an i486DX2/66 are welcome).
16363: 
16364: @cindex @file{Benchres}
16365: In
16366: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16367: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
16368: Maierhofer (presented at EuroForth '95), an indirect threaded version of
16369: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16370: several native code systems; that version of Gforth is slower on a 486
16371: than the version used here. You can find a newer version of these
16372: measurements at
16373: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
16374: find numbers for Gforth on various machines in @file{Benchres}.
16375: 
16376: @c ******************************************************************
16377: @c @node Binding to System Library, Cross Compiler, Engine, Top
16378: @c @chapter Binding to System Library
16379: 
16380: @c ****************************************************************
16381: @node Cross Compiler, Bugs, Engine, Top
16382: @chapter Cross Compiler
16383: @cindex @file{cross.fs}
16384: @cindex cross-compiler
16385: @cindex metacompiler
16386: @cindex target compiler
16387: 
16388: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16389: mostly written in Forth, including crucial parts like the outer
16390: interpreter and compiler, it needs compiled Forth code to get
16391: started. The cross compiler allows to create new images for other
16392: architectures, even running under another Forth system.
16393: 
16394: @menu
16395: * Using the Cross Compiler::    
16396: * How the Cross Compiler Works::  
16397: @end menu
16398: 
16399: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
16400: @section Using the Cross Compiler
16401: 
16402: The cross compiler uses a language that resembles Forth, but isn't. The
16403: main difference is that you can execute Forth code after definition,
16404: while you usually can't execute the code compiled by cross, because the
16405: code you are compiling is typically for a different computer than the
16406: one you are compiling on.
16407: 
16408: @c anton: This chapter is somewhat different from waht I would expect: I
16409: @c would expect an explanation of the cross language and how to create an
16410: @c application image with it.  The section explains some aspects of
16411: @c creating a Gforth kernel.
16412: 
16413: The Makefile is already set up to allow you to create kernels for new
16414: architectures with a simple make command. The generic kernels using the
16415: GCC compiled virtual machine are created in the normal build process
16416: with @code{make}. To create a embedded Gforth executable for e.g. the
16417: 8086 processor (running on a DOS machine), type
16418: 
16419: @example
16420: make kernl-8086.fi
16421: @end example
16422: 
16423: This will use the machine description from the @file{arch/8086}
16424: directory to create a new kernel. A machine file may look like that:
16425: 
16426: @example
16427: \ Parameter for target systems                         06oct92py
16428: 
16429:     4 Constant cell             \ cell size in bytes
16430:     2 Constant cell<<           \ cell shift to bytes
16431:     5 Constant cell>bit         \ cell shift to bits
16432:     8 Constant bits/char        \ bits per character
16433:     8 Constant bits/byte        \ bits per byte [default: 8]
16434:     8 Constant float            \ bytes per float
16435:     8 Constant /maxalign        \ maximum alignment in bytes
16436: false Constant bigendian        \ byte order
16437: ( true=big, false=little )
16438: 
16439: include machpc.fs               \ feature list
16440: @end example
16441: 
16442: This part is obligatory for the cross compiler itself, the feature list
16443: is used by the kernel to conditionally compile some features in and out,
16444: depending on whether the target supports these features.
16445: 
16446: There are some optional features, if you define your own primitives,
16447: have an assembler, or need special, nonstandard preparation to make the
16448: boot process work. @code{asm-include} includes an assembler,
16449: @code{prims-include} includes primitives, and @code{>boot} prepares for
16450: booting.
16451: 
16452: @example
16453: : asm-include    ." Include assembler" cr
16454:   s" arch/8086/asm.fs" included ;
16455: 
16456: : prims-include  ." Include primitives" cr
16457:   s" arch/8086/prim.fs" included ;
16458: 
16459: : >boot          ." Prepare booting" cr
16460:   s" ' boot >body into-forth 1+ !" evaluate ;
16461: @end example
16462: 
16463: These words are used as sort of macro during the cross compilation in
16464: the file @file{kernel/main.fs}. Instead of using these macros, it would
16465: be possible --- but more complicated --- to write a new kernel project
16466: file, too.
16467: 
16468: @file{kernel/main.fs} expects the machine description file name on the
16469: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16470: @code{mach-file} leaves a counted string on the stack, or
16471: @code{machine-file} leaves an address, count pair of the filename on the
16472: stack.
16473: 
16474: The feature list is typically controlled using @code{SetValue}, generic
16475: files that are used by several projects can use @code{DefaultValue}
16476: instead. Both functions work like @code{Value}, when the value isn't
16477: defined, but @code{SetValue} works like @code{to} if the value is
16478: defined, and @code{DefaultValue} doesn't set anything, if the value is
16479: defined.
16480: 
16481: @example
16482: \ generic mach file for pc gforth                       03sep97jaw
16483: 
16484: true DefaultValue NIL  \ relocating
16485: 
16486: >ENVIRON
16487: 
16488: true DefaultValue file          \ controls the presence of the
16489:                                 \ file access wordset
16490: true DefaultValue OS            \ flag to indicate a operating system
16491: 
16492: true DefaultValue prims         \ true: primitives are c-code
16493: 
16494: true DefaultValue floating      \ floating point wordset is present
16495: 
16496: true DefaultValue glocals       \ gforth locals are present
16497:                                 \ will be loaded
16498: true DefaultValue dcomps        \ double number comparisons
16499: 
16500: true DefaultValue hash          \ hashing primitives are loaded/present
16501: 
16502: true DefaultValue xconds        \ used together with glocals,
16503:                                 \ special conditionals supporting gforths'
16504:                                 \ local variables
16505: true DefaultValue header        \ save a header information
16506: 
16507: true DefaultValue backtrace     \ enables backtrace code
16508: 
16509: false DefaultValue ec
16510: false DefaultValue crlf
16511: 
16512: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16513: 
16514: &16 KB          DefaultValue stack-size
16515: &15 KB &512 +   DefaultValue fstack-size
16516: &15 KB          DefaultValue rstack-size
16517: &14 KB &512 +   DefaultValue lstack-size
16518: @end example
16519: 
16520: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
16521: @section How the Cross Compiler Works
16522: 
16523: @node Bugs, Origin, Cross Compiler, Top
16524: @appendix Bugs
16525: @cindex bug reporting
16526: 
16527: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
16528: 
16529: If you find a bug, please submit a bug report through
16530: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
16531: 
16532: @itemize @bullet
16533: @item
16534: A program (or a sequence of keyboard commands) that reproduces the bug.
16535: @item
16536: A description of what you think constitutes the buggy behaviour.
16537: @item
16538: The Gforth version used (it is announced at the start of an
16539: interactive Gforth session).
16540: @item
16541: The machine and operating system (on Unix
16542: systems @code{uname -a} will report this information).
16543: @item
16544: The installation options (you can find the configure options at the
16545: start of @file{config.status}) and configuration (@code{configure}
16546: output or @file{config.cache}).
16547: @item
16548: A complete list of changes (if any) you (or your installer) have made to the
16549: Gforth sources.
16550: @end itemize
16551: 
16552: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16553: to Report Bugs, gcc.info, GNU C Manual}.
16554: 
16555: 
16556: @node Origin, Forth-related information, Bugs, Top
16557: @appendix Authors and Ancestors of Gforth
16558: 
16559: @section Authors and Contributors
16560: @cindex authors of Gforth
16561: @cindex contributors to Gforth
16562: 
16563: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
16564: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
16565: lot to the manual.  Assemblers and disassemblers were contributed by
16566: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16567: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16568: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16569: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16570: working on automatic support for calling C libraries. Helpful comments
16571: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16572: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16573: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16574: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16575: comments from many others; thank you all, sorry for not listing you
16576: here (but digging through my mailbox to extract your names is on my
16577: to-do list).
16578: 
16579: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16580: and autoconf, among others), and to the creators of the Internet: Gforth
16581: was developed across the Internet, and its authors did not meet
16582: physically for the first 4 years of development.
16583: 
16584: @section Pedigree
16585: @cindex pedigree of Gforth
16586: 
16587: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
16588: significant part of the design of Gforth was prescribed by ANS Forth.
16589: 
16590: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
16591: 32 bit native code version of VolksForth for the Atari ST, written
16592: mostly by Dietrich Weineck.
16593: 
16594: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16595: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
16596: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
16597: 
16598: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16599: @c Forth-83 standard. !! Pedigree? When?
16600: 
16601: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16602: 1979. Robert Selzer and Bill Ragsdale developed the original
16603: implementation of fig-Forth for the 6502 based on microForth.
16604: 
16605: The principal architect of microForth was Dean Sanderson. microForth was
16606: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16607: the 1802, and subsequently implemented on the 8080, the 6800 and the
16608: Z80.
16609: 
16610: All earlier Forth systems were custom-made, usually by Charles Moore,
16611: who discovered (as he puts it) Forth during the late 60s. The first full
16612: Forth existed in 1971.
16613: 
16614: A part of the information in this section comes from
16615: @cite{@uref{http://www.forth.com/resources/evolution/index.html,The
16616: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
16617: Charles H. Moore, presented at the HOPL-II conference and preprinted
16618: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
16619: genealogical information about Forth there.  For a more general (and
16620: graphical) Forth family tree look see
16621: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16622: Forth Family Tree and Timeline}.
16623: 
16624: @c ------------------------------------------------------------------
16625: @node Forth-related information, Licenses, Origin, Top
16626: @appendix Other Forth-related information
16627: @cindex Forth-related information
16628: 
16629: @c anton: I threw most of this stuff out, because it can be found through
16630: @c the FAQ and the FAQ is more likely to be up-to-date.
16631: 
16632: @cindex comp.lang.forth
16633: @cindex frequently asked questions
16634: There is an active news group (comp.lang.forth) discussing Forth
16635: (including Gforth) and Forth-related issues. Its
16636: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16637: (frequently asked questions and their answers) contains a lot of
16638: information on Forth.  You should read it before posting to
16639: comp.lang.forth.
16640: 
16641: The ANS Forth standard is most usable in its
16642: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
16643: 
16644: @c ---------------------------------------------------
16645: @node  Licenses, Word Index, Forth-related information, Top
16646: @appendix Licenses
16647: 
16648: @menu
16649: * GNU Free Documentation License::  License for copying this manual.
16650: * Copying::                     GPL (for copying this software).
16651: @end menu
16652: 
16653: @node GNU Free Documentation License, Copying, Licenses, Licenses
16654: @appendixsec GNU Free Documentation License
16655: @include fdl.texi
16656: 
16657: @node Copying,  , GNU Free Documentation License, Licenses
16658: @appendixsec GNU GENERAL PUBLIC LICENSE
16659: @include gpl.texi
16660: 
16661: 
16662: 
16663: @c ------------------------------------------------------------------
16664: @node Word Index, Concept Index, Licenses, Top
16665: @unnumbered Word Index
16666: 
16667: This index is a list of Forth words that have ``glossary'' entries
16668: within this manual. Each word is listed with its stack effect and
16669: wordset.
16670: 
16671: @printindex fn
16672: 
16673: @c anton: the name index seems superfluous given the word and concept indices.
16674: 
16675: @c @node Name Index, Concept Index, Word Index, Top
16676: @c @unnumbered Name Index
16677: 
16678: @c This index is a list of Forth words that have ``glossary'' entries
16679: @c within this manual.
16680: 
16681: @c @printindex ky
16682: 
16683: @c -------------------------------------------------------
16684: @node Concept Index,  , Word Index, Top
16685: @unnumbered Concept and Word Index
16686: 
16687: Not all entries listed in this index are present verbatim in the
16688: text. This index also duplicates, in abbreviated form, all of the words
16689: listed in the Word Index (only the names are listed for the words here).
16690: 
16691: @printindex cp
16692: 
16693: @bye
16694: 
16695: 
16696: 

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