File:  [gforth] / gforth / doc / gforth.ds
Revision 1.139: download - view: text, annotated - select for diffs
Tue Jul 26 12:50:29 2005 UTC (18 years, 8 months ago) by pazsan
Branches: MAIN
CVS tags: HEAD
Fixed documentation bug

    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 Free Software Foundation, Inc.
   65: 
   66: @quotation
   67: Permission is granted to copy, distribute and/or modify this document
   68: under the terms of the GNU Free Documentation License, Version 1.1 or
   69: any later version published by the Free Software Foundation; with no
   70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
   71: and with the Back-Cover Texts as in (a) below.  A copy of the
   72: license is included in the section entitled ``GNU Free Documentation
   73: License.''
   74: 
   75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
   76: this GNU Manual, like GNU software.  Copies published by the Free
   77: Software Foundation raise funds for GNU development.''
   78: @end quotation
   79: @end copying
   80: 
   81: @dircategory Software development
   82: @direntry
   83: * Gforth: (gforth).             A fast interpreter for the Forth language.
   84: @end direntry
   85: @c The Texinfo manual also recommends doing this, but for Gforth it may
   86: @c  not make much sense
   87: @c @dircategory Individual utilities
   88: @c @direntry
   89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   90: @c @end direntry
   91: 
   92: @titlepage
   93: @title Gforth
   94: @subtitle for version @value{VERSION}, @value{UPDATED}
   95: @author Neal Crook
   96: @author Anton Ertl
   97: @author David Kuehling
   98: @author Bernd Paysan
   99: @author Jens Wilke
  100: @page
  101: @vskip 0pt plus 1filll
  102: @insertcopying
  103: @end titlepage
  104: 
  105: @contents
  106: 
  107: @ifnottex
  108: @node Top, Goals, (dir), (dir)
  109: @top Gforth
  110: 
  111: @insertcopying
  112: @end ifnottex
  113: 
  114: @menu
  115: * Goals::                       About the Gforth Project
  116: * Gforth Environment::          Starting (and exiting) Gforth
  117: * Tutorial::                    Hands-on Forth Tutorial
  118: * Introduction::                An introduction to ANS Forth
  119: * Words::                       Forth words available in Gforth
  120: * Error messages::              How to interpret them
  121: * Tools::                       Programming tools
  122: * ANS conformance::             Implementation-defined options etc.
  123: * Standard vs Extensions::      Should I use extensions?
  124: * Model::                       The abstract machine of Gforth
  125: * Integrating Gforth::          Forth as scripting language for applications
  126: * Emacs and Gforth::            The Gforth Mode
  127: * Image Files::                 @code{.fi} files contain compiled code
  128: * Engine::                      The inner interpreter and the primitives
  129: * Cross Compiler::              The Cross Compiler
  130: * Bugs::                        How to report them
  131: * Origin::                      Authors and ancestors of Gforth
  132: * Forth-related information::   Books and places to look on the WWW
  133: * Licenses::                    
  134: * Word Index::                  An item for each Forth word
  135: * Concept Index::               A menu covering many topics
  136: 
  137: @detailmenu
  138:  --- The Detailed Node Listing ---
  139: 
  140: Gforth Environment
  141: 
  142: * Invoking Gforth::             Getting in
  143: * Leaving Gforth::              Getting out
  144: * Command-line editing::        
  145: * Environment variables::       that affect how Gforth starts up
  146: * Gforth Files::                What gets installed and where
  147: * Gforth in pipes::             
  148: * Startup speed::               When 35ms is not fast enough ...
  149: 
  150: Forth Tutorial
  151: 
  152: * Starting Gforth Tutorial::    
  153: * Syntax Tutorial::             
  154: * Crash Course Tutorial::       
  155: * Stack Tutorial::              
  156: * Arithmetics Tutorial::        
  157: * Stack Manipulation Tutorial::  
  158: * Using files for Forth code Tutorial::  
  159: * Comments Tutorial::           
  160: * Colon Definitions Tutorial::  
  161: * Decompilation Tutorial::      
  162: * Stack-Effect Comments Tutorial::  
  163: * Types Tutorial::              
  164: * Factoring Tutorial::          
  165: * Designing the stack effect Tutorial::  
  166: * Local Variables Tutorial::    
  167: * Conditional execution Tutorial::  
  168: * Flags and Comparisons Tutorial::  
  169: * General Loops Tutorial::      
  170: * Counted loops Tutorial::      
  171: * Recursion Tutorial::          
  172: * Leaving definitions or loops Tutorial::  
  173: * Return Stack Tutorial::       
  174: * Memory Tutorial::             
  175: * Characters and Strings Tutorial::  
  176: * Alignment Tutorial::          
  177: * Files Tutorial::              
  178: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  179: * Execution Tokens Tutorial::   
  180: * Exceptions Tutorial::         
  181: * Defining Words Tutorial::     
  182: * Arrays and Records Tutorial::  
  183: * POSTPONE Tutorial::           
  184: * Literal Tutorial::            
  185: * Advanced macros Tutorial::    
  186: * Compilation Tokens Tutorial::  
  187: * Wordlists and Search Order Tutorial::  
  188: 
  189: An Introduction to ANS Forth
  190: 
  191: * Introducing the Text Interpreter::  
  192: * Stacks and Postfix notation::  
  193: * Your first definition::       
  194: * How does that work?::         
  195: * Forth is written in Forth::   
  196: * Review - elements of a Forth system::  
  197: * Where to go next::            
  198: * Exercises::                   
  199: 
  200: Forth Words
  201: 
  202: * Notation::                    
  203: * Case insensitivity::          
  204: * Comments::                    
  205: * Boolean Flags::               
  206: * Arithmetic::                  
  207: * Stack Manipulation::          
  208: * Memory::                      
  209: * Control Structures::          
  210: * Defining Words::              
  211: * Interpretation and Compilation Semantics::  
  212: * Tokens for Words::            
  213: * Compiling words::             
  214: * The Text Interpreter::        
  215: * The Input Stream::            
  216: * Word Lists::                  
  217: * Environmental Queries::       
  218: * Files::                       
  219: * Blocks::                      
  220: * Other I/O::                   
  221: * OS command line arguments::   
  222: * Locals::                      
  223: * Structures::                  
  224: * Object-oriented Forth::       
  225: * Programming Tools::           
  226: * Assembler and Code Words::    
  227: * Threading Words::             
  228: * Passing Commands to the OS::  
  229: * Keeping track of Time::       
  230: * Miscellaneous Words::         
  231: 
  232: Arithmetic
  233: 
  234: * Single precision::            
  235: * Double precision::            Double-cell integer arithmetic
  236: * Bitwise operations::          
  237: * Numeric comparison::          
  238: * Mixed precision::             Operations with single and double-cell integers
  239: * Floating Point::              
  240: 
  241: Stack Manipulation
  242: 
  243: * Data stack::                  
  244: * Floating point stack::        
  245: * Return stack::                
  246: * Locals stack::                
  247: * Stack pointer manipulation::  
  248: 
  249: Memory
  250: 
  251: * Memory model::                
  252: * Dictionary allocation::       
  253: * Heap Allocation::             
  254: * Memory Access::               
  255: * Address arithmetic::          
  256: * Memory Blocks::               
  257: 
  258: Control Structures
  259: 
  260: * Selection::                   IF ... ELSE ... ENDIF
  261: * Simple Loops::                BEGIN ...
  262: * Counted Loops::               DO
  263: * Arbitrary control structures::  
  264: * Calls and returns::           
  265: * Exception Handling::          
  266: 
  267: Defining Words
  268: 
  269: * CREATE::                      
  270: * Variables::                   Variables and user variables
  271: * Constants::                   
  272: * Values::                      Initialised variables
  273: * Colon Definitions::           
  274: * Anonymous Definitions::       Definitions without names
  275: * Supplying names::             Passing definition names as strings
  276: * User-defined Defining Words::  
  277: * Deferred words::              Allow forward references
  278: * Aliases::                     
  279: 
  280: User-defined Defining Words
  281: 
  282: * CREATE..DOES> applications::  
  283: * CREATE..DOES> details::       
  284: * Advanced does> usage example::  
  285: * @code{Const-does>}::          
  286: 
  287: Interpretation and Compilation Semantics
  288: 
  289: * Combined words::              
  290: 
  291: Tokens for Words
  292: 
  293: * Execution token::             represents execution/interpretation semantics
  294: * Compilation token::           represents compilation semantics
  295: * Name token::                  represents named words
  296: 
  297: Compiling words
  298: 
  299: * Literals::                    Compiling data values
  300: * Macros::                      Compiling words
  301: 
  302: The Text Interpreter
  303: 
  304: * Input Sources::               
  305: * Number Conversion::           
  306: * Interpret/Compile states::    
  307: * Interpreter Directives::      
  308: 
  309: Word Lists
  310: 
  311: * Vocabularies::                
  312: * Why use word lists?::         
  313: * Word list example::           
  314: 
  315: Files
  316: 
  317: * Forth source files::          
  318: * General files::               
  319: * Search Paths::                
  320: 
  321: Search Paths
  322: 
  323: * Source Search Paths::         
  324: * General Search Paths::        
  325: 
  326: Other I/O
  327: 
  328: * Simple numeric output::       Predefined formats
  329: * Formatted numeric output::    Formatted (pictured) output
  330: * String Formats::              How Forth stores strings in memory
  331: * Displaying characters and strings::  Other stuff
  332: * Input::                       Input
  333: * Pipes::                       How to create your own pipes
  334: 
  335: Locals
  336: 
  337: * Gforth locals::               
  338: * ANS Forth locals::            
  339: 
  340: Gforth locals
  341: 
  342: * Where are locals visible by name?::  
  343: * How long do locals live?::    
  344: * Locals programming style::    
  345: * Locals implementation::       
  346: 
  347: Structures
  348: 
  349: * Why explicit structure support?::  
  350: * Structure Usage::             
  351: * Structure Naming Convention::  
  352: * Structure Implementation::    
  353: * Structure Glossary::          
  354: 
  355: Object-oriented Forth
  356: 
  357: * Why object-oriented programming?::  
  358: * Object-Oriented Terminology::  
  359: * Objects::                     
  360: * OOF::                         
  361: * Mini-OOF::                    
  362: * Comparison with other object models::  
  363: 
  364: The @file{objects.fs} model
  365: 
  366: * Properties of the Objects model::  
  367: * Basic Objects Usage::         
  368: * The Objects base class::      
  369: * Creating objects::            
  370: * Object-Oriented Programming Style::  
  371: * Class Binding::               
  372: * Method conveniences::         
  373: * Classes and Scoping::         
  374: * Dividing classes::            
  375: * Object Interfaces::           
  376: * Objects Implementation::      
  377: * Objects Glossary::            
  378: 
  379: The @file{oof.fs} model
  380: 
  381: * Properties of the OOF model::  
  382: * Basic OOF Usage::             
  383: * The OOF base class::          
  384: * Class Declaration::           
  385: * Class Implementation::        
  386: 
  387: The @file{mini-oof.fs} model
  388: 
  389: * Basic Mini-OOF Usage::        
  390: * Mini-OOF Example::            
  391: * Mini-OOF Implementation::     
  392: 
  393: Programming Tools
  394: 
  395: * Examining::                   
  396: * Forgetting words::            
  397: * Debugging::                   Simple and quick.
  398: * Assertions::                  Making your programs self-checking.
  399: * Singlestep Debugger::         Executing your program word by word.
  400: 
  401: Assembler and Code Words
  402: 
  403: * Code and ;code::              
  404: * Common Assembler::            Assembler Syntax
  405: * Common Disassembler::         
  406: * 386 Assembler::               Deviations and special cases
  407: * Alpha Assembler::             Deviations and special cases
  408: * MIPS assembler::              Deviations and special cases
  409: * Other assemblers::            How to write them
  410: 
  411: Tools
  412: 
  413: * ANS Report::                  Report the words used, sorted by wordset.
  414: * Stack depth changes::         Where does this stack item come from?
  415: 
  416: ANS conformance
  417: 
  418: * The Core Words::              
  419: * The optional Block word set::  
  420: * The optional Double Number word set::  
  421: * The optional Exception word set::  
  422: * The optional Facility word set::  
  423: * The optional File-Access word set::  
  424: * The optional Floating-Point word set::  
  425: * The optional Locals word set::  
  426: * The optional Memory-Allocation word set::  
  427: * The optional Programming-Tools word set::  
  428: * The optional Search-Order word set::  
  429: 
  430: The Core Words
  431: 
  432: * core-idef::                   Implementation Defined Options                   
  433: * core-ambcond::                Ambiguous Conditions                
  434: * core-other::                  Other System Documentation                  
  435: 
  436: The optional Block word set
  437: 
  438: * block-idef::                  Implementation Defined Options
  439: * block-ambcond::               Ambiguous Conditions               
  440: * block-other::                 Other System Documentation                 
  441: 
  442: The optional Double Number word set
  443: 
  444: * double-ambcond::              Ambiguous Conditions              
  445: 
  446: The optional Exception word set
  447: 
  448: * exception-idef::              Implementation Defined Options              
  449: 
  450: The optional Facility word set
  451: 
  452: * facility-idef::               Implementation Defined Options               
  453: * facility-ambcond::            Ambiguous Conditions            
  454: 
  455: The optional File-Access word set
  456: 
  457: * file-idef::                   Implementation Defined Options
  458: * file-ambcond::                Ambiguous Conditions                
  459: 
  460: The optional Floating-Point word set
  461: 
  462: * floating-idef::               Implementation Defined Options
  463: * floating-ambcond::            Ambiguous Conditions            
  464: 
  465: The optional Locals word set
  466: 
  467: * locals-idef::                 Implementation Defined Options                 
  468: * locals-ambcond::              Ambiguous Conditions              
  469: 
  470: The optional Memory-Allocation word set
  471: 
  472: * memory-idef::                 Implementation Defined Options                 
  473: 
  474: The optional Programming-Tools word set
  475: 
  476: * programming-idef::            Implementation Defined Options            
  477: * programming-ambcond::         Ambiguous Conditions         
  478: 
  479: The optional Search-Order word set
  480: 
  481: * search-idef::                 Implementation Defined Options                 
  482: * search-ambcond::              Ambiguous Conditions              
  483: 
  484: Emacs and Gforth
  485: 
  486: * Installing gforth.el::        Making Emacs aware of Forth.
  487: * Emacs Tags::                  Viewing the source of a word in Emacs.
  488: * Hilighting::                  Making Forth code look prettier.
  489: * Auto-Indentation::            Customizing auto-indentation.
  490: * Blocks Files::                Reading and writing blocks files.
  491: 
  492: Image Files
  493: 
  494: * Image Licensing Issues::      Distribution terms for images.
  495: * Image File Background::       Why have image files?
  496: * Non-Relocatable Image Files::  don't always work.
  497: * Data-Relocatable Image Files::  are better.
  498: * Fully Relocatable Image Files::  better yet.
  499: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  500: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  501: * Modifying the Startup Sequence::  and turnkey applications.
  502: 
  503: Fully Relocatable Image Files
  504: 
  505: * gforthmi::                    The normal way
  506: * cross.fs::                    The hard way
  507: 
  508: Engine
  509: 
  510: * Portability::                 
  511: * Threading::                   
  512: * Primitives::                  
  513: * Performance::                 
  514: 
  515: Threading
  516: 
  517: * Scheduling::                  
  518: * Direct or Indirect Threaded?::  
  519: * Dynamic Superinstructions::   
  520: * DOES>::                       
  521: 
  522: Primitives
  523: 
  524: * Automatic Generation::        
  525: * TOS Optimization::            
  526: * Produced code::               
  527: 
  528: Cross Compiler
  529: 
  530: * Using the Cross Compiler::    
  531: * How the Cross Compiler Works::  
  532: 
  533: Licenses
  534: 
  535: * GNU Free Documentation License::  License for copying this manual.
  536: * Copying::                         GPL (for copying this software).
  537: 
  538: @end detailmenu
  539: @end menu
  540: 
  541: @c ----------------------------------------------------------
  542: @iftex
  543: @unnumbered Preface
  544: @cindex Preface
  545: This manual documents Gforth. Some introductory material is provided for
  546: readers who are unfamiliar with Forth or who are migrating to Gforth
  547: from other Forth compilers. However, this manual is primarily a
  548: reference manual.
  549: @end iftex
  550: 
  551: @comment TODO much more blurb here.
  552: 
  553: @c ******************************************************************
  554: @node Goals, Gforth Environment, Top, Top
  555: @comment node-name,     next,           previous, up
  556: @chapter Goals of Gforth
  557: @cindex goals of the Gforth project
  558: The goal of the Gforth Project is to develop a standard model for
  559: ANS Forth. This can be split into several subgoals:
  560: 
  561: @itemize @bullet
  562: @item
  563: Gforth should conform to the ANS Forth Standard.
  564: @item
  565: It should be a model, i.e. it should define all the
  566: implementation-dependent things.
  567: @item
  568: It should become standard, i.e. widely accepted and used. This goal
  569: is the most difficult one.
  570: @end itemize
  571: 
  572: To achieve these goals Gforth should be
  573: @itemize @bullet
  574: @item
  575: Similar to previous models (fig-Forth, F83)
  576: @item
  577: Powerful. It should provide for all the things that are considered
  578: necessary today and even some that are not yet considered necessary.
  579: @item
  580: Efficient. It should not get the reputation of being exceptionally
  581: slow.
  582: @item
  583: Free.
  584: @item
  585: Available on many machines/easy to port.
  586: @end itemize
  587: 
  588: Have we achieved these goals? Gforth conforms to the ANS Forth
  589: standard. It may be considered a model, but we have not yet documented
  590: which parts of the model are stable and which parts we are likely to
  591: change. It certainly has not yet become a de facto standard, but it
  592: appears to be quite popular. It has some similarities to and some
  593: differences from previous models. It has some powerful features, but not
  594: yet everything that we envisioned. We certainly have achieved our
  595: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  596: the bar was raised when the major commercial Forth vendors switched to
  597: native code compilers.}.  It is free and available on many machines.
  598: 
  599: @c ******************************************************************
  600: @node Gforth Environment, Tutorial, Goals, Top
  601: @chapter Gforth Environment
  602: @cindex Gforth environment
  603: 
  604: Note: ultimately, the Gforth man page will be auto-generated from the
  605: material in this chapter.
  606: 
  607: @menu
  608: * Invoking Gforth::             Getting in
  609: * Leaving Gforth::              Getting out
  610: * Command-line editing::        
  611: * Environment variables::       that affect how Gforth starts up
  612: * Gforth Files::                What gets installed and where
  613: * Gforth in pipes::             
  614: * Startup speed::               When 35ms is not fast enough ...
  615: @end menu
  616: 
  617: For related information about the creation of images see @ref{Image Files}.
  618: 
  619: @comment ----------------------------------------------
  620: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  621: @section Invoking Gforth
  622: @cindex invoking Gforth
  623: @cindex running Gforth
  624: @cindex command-line options
  625: @cindex options on the command line
  626: @cindex flags on the command line
  627: 
  628: Gforth is made up of two parts; an executable ``engine'' (named
  629: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  630: will usually just say @code{gforth} -- this automatically loads the
  631: default image file @file{gforth.fi}. In many other cases the default
  632: Gforth image will be invoked like this:
  633: @example
  634: gforth [file | -e forth-code] ...
  635: @end example
  636: @noindent
  637: This interprets the contents of the files and the Forth code in the order they
  638: are given.
  639: 
  640: In addition to the @command{gforth} engine, there is also an engine
  641: called @command{gforth-fast}, which is faster, but gives less
  642: informative error messages (@pxref{Error messages}) and may catch some
  643: stack underflows later or not at all.  You should use it for debugged,
  644: performance-critical programs.
  645: 
  646: Moreover, there is an engine called @command{gforth-itc}, which is
  647: useful in some backwards-compatibility situations (@pxref{Direct or
  648: Indirect Threaded?}).
  649: 
  650: In general, the command line looks like this:
  651: 
  652: @example
  653: gforth[-fast] [engine options] [image options]
  654: @end example
  655: 
  656: The engine options must come before the rest of the command
  657: line. They are:
  658: 
  659: @table @code
  660: @cindex -i, command-line option
  661: @cindex --image-file, command-line option
  662: @item --image-file @i{file}
  663: @itemx -i @i{file}
  664: Loads the Forth image @i{file} instead of the default
  665: @file{gforth.fi} (@pxref{Image Files}).
  666: 
  667: @cindex --appl-image, command-line option
  668: @item --appl-image @i{file}
  669: Loads the image @i{file} and leaves all further command-line arguments
  670: to the image (instead of processing them as engine options).  This is
  671: useful for building executable application images on Unix, built with
  672: @code{gforthmi --application ...}.
  673: 
  674: @cindex --path, command-line option
  675: @cindex -p, command-line option
  676: @item --path @i{path}
  677: @itemx -p @i{path}
  678: Uses @i{path} for searching the image file and Forth source code files
  679: instead of the default in the environment variable @code{GFORTHPATH} or
  680: the path specified at installation time (e.g.,
  681: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  682: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  683: 
  684: @cindex --dictionary-size, command-line option
  685: @cindex -m, command-line option
  686: @cindex @i{size} parameters for command-line options
  687: @cindex size of the dictionary and the stacks
  688: @item --dictionary-size @i{size}
  689: @itemx -m @i{size}
  690: Allocate @i{size} space for the Forth dictionary space instead of
  691: using the default specified in the image (typically 256K). The
  692: @i{size} specification for this and subsequent options consists of
  693: an integer and a unit (e.g.,
  694: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  695: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  696: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  697: @code{e} is used.
  698: 
  699: @cindex --data-stack-size, command-line option
  700: @cindex -d, command-line option
  701: @item --data-stack-size @i{size}
  702: @itemx -d @i{size}
  703: Allocate @i{size} space for the data stack instead of using the
  704: default specified in the image (typically 16K).
  705: 
  706: @cindex --return-stack-size, command-line option
  707: @cindex -r, command-line option
  708: @item --return-stack-size @i{size}
  709: @itemx -r @i{size}
  710: Allocate @i{size} space for the return stack instead of using the
  711: default specified in the image (typically 15K).
  712: 
  713: @cindex --fp-stack-size, command-line option
  714: @cindex -f, command-line option
  715: @item --fp-stack-size @i{size}
  716: @itemx -f @i{size}
  717: Allocate @i{size} space for the floating point stack instead of
  718: using the default specified in the image (typically 15.5K). In this case
  719: the unit specifier @code{e} refers to floating point numbers.
  720: 
  721: @cindex --locals-stack-size, command-line option
  722: @cindex -l, command-line option
  723: @item --locals-stack-size @i{size}
  724: @itemx -l @i{size}
  725: Allocate @i{size} space for the locals stack instead of using the
  726: default specified in the image (typically 14.5K).
  727: 
  728: @cindex -h, command-line option
  729: @cindex --help, command-line option
  730: @item --help
  731: @itemx -h
  732: Print a message about the command-line options
  733: 
  734: @cindex -v, command-line option
  735: @cindex --version, command-line option
  736: @item --version
  737: @itemx -v
  738: Print version and exit
  739: 
  740: @cindex --debug, command-line option
  741: @item --debug
  742: Print some information useful for debugging on startup.
  743: 
  744: @cindex --offset-image, command-line option
  745: @item --offset-image
  746: Start the dictionary at a slightly different position than would be used
  747: otherwise (useful for creating data-relocatable images,
  748: @pxref{Data-Relocatable Image Files}).
  749: 
  750: @cindex --no-offset-im, command-line option
  751: @item --no-offset-im
  752: Start the dictionary at the normal position.
  753: 
  754: @cindex --clear-dictionary, command-line option
  755: @item --clear-dictionary
  756: Initialize all bytes in the dictionary to 0 before loading the image
  757: (@pxref{Data-Relocatable Image Files}).
  758: 
  759: @cindex --die-on-signal, command-line-option
  760: @item --die-on-signal
  761: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  762: or the segmentation violation SIGSEGV) by translating it into a Forth
  763: @code{THROW}. With this option, Gforth exits if it receives such a
  764: signal. This option is useful when the engine and/or the image might be
  765: severely broken (such that it causes another signal before recovering
  766: from the first); this option avoids endless loops in such cases.
  767: 
  768: @cindex --no-dynamic, command-line option
  769: @cindex --dynamic, command-line option
  770: @item --no-dynamic
  771: @item --dynamic
  772: Disable or enable dynamic superinstructions with replication
  773: (@pxref{Dynamic Superinstructions}).
  774: 
  775: @cindex --no-super, command-line option
  776: @item --no-super
  777: Disable dynamic superinstructions, use just dynamic replication; this is
  778: useful if you want to patch threaded code (@pxref{Dynamic
  779: Superinstructions}).
  780: 
  781: @cindex --ss-number, command-line option
  782: @item --ss-number=@var{N}
  783: Use only the first @var{N} static superinstructions compiled into the
  784: engine (default: use them all; note that only @code{gforth-fast} has
  785: any).  This option is useful for measuring the performance impact of
  786: static superinstructions.
  787: 
  788: @cindex --ss-min-..., command-line options
  789: @item --ss-min-codesize
  790: @item --ss-min-ls
  791: @item --ss-min-lsu
  792: @item --ss-min-nexts
  793: Use specified metric for determining the cost of a primitive or static
  794: superinstruction for static superinstruction selection.  @code{Codesize}
  795: is the native code size of the primive or static superinstruction,
  796: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  797: loads, stores, and updates, and @code{nexts} is the number of dispatches
  798: (not taking dynamic superinstructions into account), i.e. every
  799: primitive or static superinstruction has cost 1. Default:
  800: @code{codesize} if you use dynamic code generation, otherwise
  801: @code{nexts}.
  802: 
  803: @cindex --ss-greedy, command-line option
  804: @item --ss-greedy
  805: This option is useful for measuring the performance impact of static
  806: superinstructions.  By default, an optimal shortest-path algorithm is
  807: used for selecting static superinstructions.  With @option{--ss-greedy}
  808: this algorithm is modified to assume that anything after the static
  809: superinstruction currently under consideration is not combined into
  810: static superinstructions.  With @option{--ss-min-nexts} this produces
  811: the same result as a greedy algorithm that always selects the longest
  812: superinstruction available at the moment.  E.g., if there are
  813: superinstructions AB and BCD, then for the sequence A B C D the optimal
  814: algorithm will select A BCD and the greedy algorithm will select AB C D.
  815: 
  816: @cindex --print-metrics, command-line option
  817: @item --print-metrics
  818: Prints some metrics used during static superinstruction selection:
  819: @code{code size} is the actual size of the dynamically generated code.
  820: @code{Metric codesize} is the sum of the codesize metrics as seen by
  821: static superinstruction selection; there is a difference from @code{code
  822: size}, because not all primitives and static superinstructions are
  823: compiled into dynamically generated code, and because of markers.  The
  824: other metrics correspond to the @option{ss-min-...} options.  This
  825: option is useful for evaluating the effects of the @option{--ss-...}
  826: options.
  827: 
  828: @end table
  829: 
  830: @cindex loading files at startup
  831: @cindex executing code on startup
  832: @cindex batch processing with Gforth
  833: As explained above, the image-specific command-line arguments for the
  834: default image @file{gforth.fi} consist of a sequence of filenames and
  835: @code{-e @var{forth-code}} options that are interpreted in the sequence
  836: in which they are given. The @code{-e @var{forth-code}} or
  837: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  838: option takes only one argument; if you want to evaluate more Forth
  839: words, you have to quote them or use @code{-e} several times. To exit
  840: after processing the command line (instead of entering interactive mode)
  841: append @code{-e bye} to the command line.  You can also process the
  842: command-line arguments with a Forth program (@pxref{OS command line
  843: arguments}).
  844: 
  845: @cindex versions, invoking other versions of Gforth
  846: If you have several versions of Gforth installed, @code{gforth} will
  847: invoke the version that was installed last. @code{gforth-@i{version}}
  848: invokes a specific version. If your environment contains the variable
  849: @code{GFORTHPATH}, you may want to override it by using the
  850: @code{--path} option.
  851: 
  852: Not yet implemented:
  853: On startup the system first executes the system initialization file
  854: (unless the option @code{--no-init-file} is given; note that the system
  855: resulting from using this option may not be ANS Forth conformant). Then
  856: the user initialization file @file{.gforth.fs} is executed, unless the
  857: option @code{--no-rc} is given; this file is searched for in @file{.},
  858: then in @file{~}, then in the normal path (see above).
  859: 
  860: 
  861: 
  862: @comment ----------------------------------------------
  863: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  864: @section Leaving Gforth
  865: @cindex Gforth - leaving
  866: @cindex leaving Gforth
  867: 
  868: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  869: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  870: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  871: data are discarded.  For ways of saving the state of the system before
  872: leaving Gforth see @ref{Image Files}.
  873: 
  874: doc-bye
  875: 
  876: 
  877: @comment ----------------------------------------------
  878: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  879: @section Command-line editing
  880: @cindex command-line editing
  881: 
  882: Gforth maintains a history file that records every line that you type to
  883: the text interpreter. This file is preserved between sessions, and is
  884: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  885: repeatedly you can recall successively older commands from this (or
  886: previous) session(s). The full list of command-line editing facilities is:
  887: 
  888: @itemize @bullet
  889: @item
  890: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  891: commands from the history buffer.
  892: @item
  893: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  894: from the history buffer.
  895: @item
  896: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  897: @item
  898: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  899: @item
  900: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  901: closing up the line.
  902: @item
  903: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  904: @item
  905: @kbd{Ctrl-a} to move the cursor to the start of the line.
  906: @item
  907: @kbd{Ctrl-e} to move the cursor to the end of the line.
  908: @item
  909: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  910: line.
  911: @item
  912: @key{TAB} to step through all possible full-word completions of the word
  913: currently being typed.
  914: @item
  915: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  916: using @code{bye}). 
  917: @item
  918: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  919: character under the cursor.
  920: @end itemize
  921: 
  922: When editing, displayable characters are inserted to the left of the
  923: cursor position; the line is always in ``insert'' (as opposed to
  924: ``overstrike'') mode.
  925: 
  926: @cindex history file
  927: @cindex @file{.gforth-history}
  928: On Unix systems, the history file is @file{~/.gforth-history} by
  929: default@footnote{i.e. it is stored in the user's home directory.}. You
  930: can find out the name and location of your history file using:
  931: 
  932: @example 
  933: history-file type \ Unix-class systems
  934: 
  935: history-file type \ Other systems
  936: history-dir  type
  937: @end example
  938: 
  939: If you enter long definitions by hand, you can use a text editor to
  940: paste them out of the history file into a Forth source file for reuse at
  941: a later time.
  942: 
  943: Gforth never trims the size of the history file, so you should do this
  944: periodically, if necessary.
  945: 
  946: @comment this is all defined in history.fs
  947: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  948: @comment chosen?
  949: 
  950: 
  951: @comment ----------------------------------------------
  952: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  953: @section Environment variables
  954: @cindex environment variables
  955: 
  956: Gforth uses these environment variables:
  957: 
  958: @itemize @bullet
  959: @item
  960: @cindex @code{GFORTHHIST} -- environment variable
  961: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  962: open/create the history file, @file{.gforth-history}. Default:
  963: @code{$HOME}.
  964: 
  965: @item
  966: @cindex @code{GFORTHPATH} -- environment variable
  967: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
  968: for Forth source-code files.
  969: 
  970: @item
  971: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
  972: 
  973: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
  974: of @code{system} before passing it to C's @code{system()}.  Default:
  975: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
  976: and the command are directly concatenated, so if a space between them is
  977: necessary, append it to the prefix.
  978: 
  979: @item
  980: @cindex @code{GFORTH} -- environment variable
  981: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
  982: 
  983: @item
  984: @cindex @code{GFORTHD} -- environment variable
  985: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
  986: 
  987: @item
  988: @cindex @code{TMP}, @code{TEMP} - environment variable
  989: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
  990: location for the history file.
  991: @end itemize
  992: 
  993: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
  994: @comment mentioning these.
  995: 
  996: All the Gforth environment variables default to sensible values if they
  997: are not set.
  998: 
  999: 
 1000: @comment ----------------------------------------------
 1001: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1002: @section Gforth files
 1003: @cindex Gforth files
 1004: 
 1005: When you install Gforth on a Unix system, it installs files in these
 1006: locations by default:
 1007: 
 1008: @itemize @bullet
 1009: @item
 1010: @file{/usr/local/bin/gforth}
 1011: @item
 1012: @file{/usr/local/bin/gforthmi}
 1013: @item
 1014: @file{/usr/local/man/man1/gforth.1} - man page.
 1015: @item
 1016: @file{/usr/local/info} - the Info version of this manual.
 1017: @item
 1018: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1019: @item
 1020: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1021: @item
 1022: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1023: @item
 1024: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1025: @end itemize
 1026: 
 1027: You can select different places for installation by using
 1028: @code{configure} options (listed with @code{configure --help}).
 1029: 
 1030: @comment ----------------------------------------------
 1031: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1032: @section Gforth in pipes
 1033: @cindex pipes, Gforth as part of
 1034: 
 1035: Gforth can be used in pipes created elsewhere (described here).  It can
 1036: also create pipes on its own (@pxref{Pipes}).
 1037: 
 1038: @cindex input from pipes
 1039: If you pipe into Gforth, your program should read with @code{read-file}
 1040: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1041: @code{Key} does not recognize the end of input.  Words like
 1042: @code{accept} echo the input and are therefore usually not useful for
 1043: reading from a pipe.  You have to invoke the Forth program with an OS
 1044: command-line option, as you have no chance to use the Forth command line
 1045: (the text interpreter would try to interpret the pipe input).
 1046: 
 1047: @cindex output in pipes
 1048: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1049: 
 1050: @cindex silent exiting from Gforth
 1051: When you write to a pipe that has been closed at the other end, Gforth
 1052: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1053: into the exception @code{broken-pipe-error}.  If your application does
 1054: not catch that exception, the system catches it and exits, usually
 1055: silently (unless you were working on the Forth command line; then it
 1056: prints an error message and exits).  This is usually the desired
 1057: behaviour.
 1058: 
 1059: If you do not like this behaviour, you have to catch the exception
 1060: yourself, and react to it.
 1061: 
 1062: Here's an example of an invocation of Gforth that is usable in a pipe:
 1063: 
 1064: @example
 1065: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1066:  type repeat ; foo bye"
 1067: @end example
 1068: 
 1069: This example just copies the input verbatim to the output.  A very
 1070: simple pipe containing this example looks like this:
 1071: 
 1072: @example
 1073: cat startup.fs |
 1074: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1075:  type repeat ; foo bye"|
 1076: head
 1077: @end example
 1078: 
 1079: @cindex stderr and pipes
 1080: Pipes involving Gforth's @code{stderr} output do not work.
 1081: 
 1082: @comment ----------------------------------------------
 1083: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1084: @section Startup speed
 1085: @cindex Startup speed
 1086: @cindex speed, startup
 1087: 
 1088: If Gforth is used for CGI scripts or in shell scripts, its startup
 1089: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1090: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1091: system time.
 1092: 
 1093: If startup speed is a problem, you may consider the following ways to
 1094: improve it; or you may consider ways to reduce the number of startups
 1095: (for example, by using Fast-CGI).
 1096: 
 1097: An easy step that influences Gforth startup speed is the use of the
 1098: @option{--no-dynamic} option; this decreases image loading speed, but
 1099: increases compile-time and run-time.
 1100: 
 1101: Another step to improve startup speed is to statically link Gforth, by
 1102: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1103: the code and will therefore slow down the first invocation, but
 1104: subsequent invocations avoid the dynamic linking overhead.  Another
 1105: disadvantage is that Gforth won't profit from library upgrades.  As a
 1106: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1107: 8.2ms system time.
 1108: 
 1109: The next step to improve startup speed is to use a non-relocatable image
 1110: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1111: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1112: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1113: and a part of the copy-on-write overhead.  The disadvantage is that the
 1114: non-relocatable image does not work if the OS gives Gforth a different
 1115: address for the dictionary, for whatever reason; so you better provide a
 1116: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1117: bye} takes about 15.3ms user and 7.5ms system time.
 1118: 
 1119: The final step is to disable dictionary hashing in Gforth.  Gforth
 1120: builds the hash table on startup, which takes much of the startup
 1121: overhead. You can do this by commenting out the @code{include hash.fs}
 1122: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1123: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1124: The disadvantages are that functionality like @code{table} and
 1125: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1126: now takes much longer. So, you should only use this method if there is
 1127: no significant text interpretation to perform (the script should be
 1128: compiled into the image, amongst other things).  @code{gforth-static -i
 1129: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1130: 
 1131: @c ******************************************************************
 1132: @node Tutorial, Introduction, Gforth Environment, Top
 1133: @chapter Forth Tutorial
 1134: @cindex Tutorial
 1135: @cindex Forth Tutorial
 1136: 
 1137: @c Topics from nac's Introduction that could be mentioned:
 1138: @c press <ret> after each line
 1139: @c Prompt
 1140: @c numbers vs. words in dictionary on text interpretation
 1141: @c what happens on redefinition
 1142: @c parsing words (in particular, defining words)
 1143: 
 1144: The difference of this chapter from the Introduction
 1145: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1146: be used while sitting in front of a computer, and covers much more
 1147: material, but does not explain how the Forth system works.
 1148: 
 1149: This tutorial can be used with any ANS-compliant Forth; any
 1150: Gforth-specific features are marked as such and you can skip them if you
 1151: work with another Forth.  This tutorial does not explain all features of
 1152: Forth, just enough to get you started and give you some ideas about the
 1153: facilities available in Forth.  Read the rest of the manual and the
 1154: standard when you are through this.
 1155: 
 1156: The intended way to use this tutorial is that you work through it while
 1157: sitting in front of the console, take a look at the examples and predict
 1158: what they will do, then try them out; if the outcome is not as expected,
 1159: find out why (e.g., by trying out variations of the example), so you
 1160: understand what's going on.  There are also some assignments that you
 1161: should solve.
 1162: 
 1163: This tutorial assumes that you have programmed before and know what,
 1164: e.g., a loop is.
 1165: 
 1166: @c !! explain compat library
 1167: 
 1168: @menu
 1169: * Starting Gforth Tutorial::    
 1170: * Syntax Tutorial::             
 1171: * Crash Course Tutorial::       
 1172: * Stack Tutorial::              
 1173: * Arithmetics Tutorial::        
 1174: * Stack Manipulation Tutorial::  
 1175: * Using files for Forth code Tutorial::  
 1176: * Comments Tutorial::           
 1177: * Colon Definitions Tutorial::  
 1178: * Decompilation Tutorial::      
 1179: * Stack-Effect Comments Tutorial::  
 1180: * Types Tutorial::              
 1181: * Factoring Tutorial::          
 1182: * Designing the stack effect Tutorial::  
 1183: * Local Variables Tutorial::    
 1184: * Conditional execution Tutorial::  
 1185: * Flags and Comparisons Tutorial::  
 1186: * General Loops Tutorial::      
 1187: * Counted loops Tutorial::      
 1188: * Recursion Tutorial::          
 1189: * Leaving definitions or loops Tutorial::  
 1190: * Return Stack Tutorial::       
 1191: * Memory Tutorial::             
 1192: * Characters and Strings Tutorial::  
 1193: * Alignment Tutorial::          
 1194: * Files Tutorial::              
 1195: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1196: * Execution Tokens Tutorial::   
 1197: * Exceptions Tutorial::         
 1198: * Defining Words Tutorial::     
 1199: * Arrays and Records Tutorial::  
 1200: * POSTPONE Tutorial::           
 1201: * Literal Tutorial::            
 1202: * Advanced macros Tutorial::    
 1203: * Compilation Tokens Tutorial::  
 1204: * Wordlists and Search Order Tutorial::  
 1205: @end menu
 1206: 
 1207: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1208: @section Starting Gforth
 1209: @cindex starting Gforth tutorial
 1210: You can start Gforth by typing its name:
 1211: 
 1212: @example
 1213: gforth
 1214: @end example
 1215: 
 1216: That puts you into interactive mode; you can leave Gforth by typing
 1217: @code{bye}.  While in Gforth, you can edit the command line and access
 1218: the command line history with cursor keys, similar to bash.
 1219: 
 1220: 
 1221: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1222: @section Syntax
 1223: @cindex syntax tutorial
 1224: 
 1225: A @dfn{word} is a sequence of arbitrary characters (expcept white
 1226: space).  Words are separated by white space.  E.g., each of the
 1227: following lines contains exactly one word:
 1228: 
 1229: @example
 1230: word
 1231: !@@#$%^&*()
 1232: 1234567890
 1233: 5!a
 1234: @end example
 1235: 
 1236: A frequent beginner's error is to leave away necessary white space,
 1237: resulting in an error like @samp{Undefined word}; so if you see such an
 1238: error, check if you have put spaces wherever necessary.
 1239: 
 1240: @example
 1241: ." hello, world" \ correct
 1242: ."hello, world"  \ gives an "Undefined word" error
 1243: @end example
 1244: 
 1245: Gforth and most other Forth systems ignore differences in case (they are
 1246: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1247: your system is case-sensitive, you may have to type all the examples
 1248: given here in upper case.
 1249: 
 1250: 
 1251: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1252: @section Crash Course
 1253: 
 1254: Type
 1255: 
 1256: @example
 1257: 0 0 !
 1258: here execute
 1259: ' catch >body 20 erase abort
 1260: ' (quit) >body 20 erase
 1261: @end example
 1262: 
 1263: The last two examples are guaranteed to destroy parts of Gforth (and
 1264: most other systems), so you better leave Gforth afterwards (if it has
 1265: not finished by itself).  On some systems you may have to kill gforth
 1266: from outside (e.g., in Unix with @code{kill}).
 1267: 
 1268: Now that you know how to produce crashes (and that there's not much to
 1269: them), let's learn how to produce meaningful programs.
 1270: 
 1271: 
 1272: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1273: @section Stack
 1274: @cindex stack tutorial
 1275: 
 1276: The most obvious feature of Forth is the stack.  When you type in a
 1277: number, it is pushed on the stack.  You can display the content of the
 1278: stack with @code{.s}.
 1279: 
 1280: @example
 1281: 1 2 .s
 1282: 3 .s
 1283: @end example
 1284: 
 1285: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1286: appear in @code{.s} output as they appeared in the input.
 1287: 
 1288: You can print the top of stack element with @code{.}.
 1289: 
 1290: @example
 1291: 1 2 3 . . .
 1292: @end example
 1293: 
 1294: In general, words consume their stack arguments (@code{.s} is an
 1295: exception).
 1296: 
 1297: @assignment
 1298: What does the stack contain after @code{5 6 7 .}?
 1299: @endassignment
 1300: 
 1301: 
 1302: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1303: @section Arithmetics
 1304: @cindex arithmetics tutorial
 1305: 
 1306: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1307: operate on the top two stack items:
 1308: 
 1309: @example
 1310: 2 2 .s
 1311: + .s
 1312: .
 1313: 2 1 - .
 1314: 7 3 mod .
 1315: @end example
 1316: 
 1317: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1318: as in the corresponding infix expression (this is generally the case in
 1319: Forth).
 1320: 
 1321: Parentheses are superfluous (and not available), because the order of
 1322: the words unambiguously determines the order of evaluation and the
 1323: operands:
 1324: 
 1325: @example
 1326: 3 4 + 5 * .
 1327: 3 4 5 * + .
 1328: @end example
 1329: 
 1330: @assignment
 1331: What are the infix expressions corresponding to the Forth code above?
 1332: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1333: known as Postfix or RPN (Reverse Polish Notation).}.
 1334: @endassignment
 1335: 
 1336: To change the sign, use @code{negate}:
 1337: 
 1338: @example
 1339: 2 negate .
 1340: @end example
 1341: 
 1342: @assignment
 1343: Convert -(-3)*4-5 to Forth.
 1344: @endassignment
 1345: 
 1346: @code{/mod} performs both @code{/} and @code{mod}.
 1347: 
 1348: @example
 1349: 7 3 /mod . .
 1350: @end example
 1351: 
 1352: Reference: @ref{Arithmetic}.
 1353: 
 1354: 
 1355: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1356: @section Stack Manipulation
 1357: @cindex stack manipulation tutorial
 1358: 
 1359: Stack manipulation words rearrange the data on the stack.
 1360: 
 1361: @example
 1362: 1 .s drop .s
 1363: 1 .s dup .s drop drop .s
 1364: 1 2 .s over .s drop drop drop
 1365: 1 2 .s swap .s drop drop
 1366: 1 2 3 .s rot .s drop drop drop
 1367: @end example
 1368: 
 1369: These are the most important stack manipulation words.  There are also
 1370: variants that manipulate twice as many stack items:
 1371: 
 1372: @example
 1373: 1 2 3 4 .s 2swap .s 2drop 2drop
 1374: @end example
 1375: 
 1376: Two more stack manipulation words are:
 1377: 
 1378: @example
 1379: 1 2 .s nip .s drop
 1380: 1 2 .s tuck .s 2drop drop
 1381: @end example
 1382: 
 1383: @assignment
 1384: Replace @code{nip} and @code{tuck} with combinations of other stack
 1385: manipulation words.
 1386: 
 1387: @example
 1388: Given:          How do you get:
 1389: 1 2 3           3 2 1           
 1390: 1 2 3           1 2 3 2                 
 1391: 1 2 3           1 2 3 3                 
 1392: 1 2 3           1 3 3           
 1393: 1 2 3           2 1 3           
 1394: 1 2 3 4         4 3 2 1         
 1395: 1 2 3           1 2 3 1 2 3             
 1396: 1 2 3 4         1 2 3 4 1 2             
 1397: 1 2 3
 1398: 1 2 3           1 2 3 4                 
 1399: 1 2 3           1 3             
 1400: @end example
 1401: @endassignment
 1402: 
 1403: @example
 1404: 5 dup * .
 1405: @end example
 1406: 
 1407: @assignment
 1408: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1409: Write a piece of Forth code that expects two numbers on the stack
 1410: (@var{a} and @var{b}, with @var{b} on top) and computes
 1411: @code{(a-b)(a+1)}.
 1412: @endassignment
 1413: 
 1414: Reference: @ref{Stack Manipulation}.
 1415: 
 1416: 
 1417: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1418: @section Using files for Forth code
 1419: @cindex loading Forth code, tutorial
 1420: @cindex files containing Forth code, tutorial
 1421: 
 1422: While working at the Forth command line is convenient for one-line
 1423: examples and short one-off code, you probably want to store your source
 1424: code in files for convenient editing and persistence.  You can use your
 1425: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1426: Gforth}) to create @var{file.fs} and use
 1427: 
 1428: @example
 1429: s" @var{file.fs}" included
 1430: @end example
 1431: 
 1432: to load it into your Forth system.  The file name extension I use for
 1433: Forth files is @samp{.fs}.
 1434: 
 1435: You can easily start Gforth with some files loaded like this:
 1436: 
 1437: @example
 1438: gforth @var{file1.fs} @var{file2.fs}
 1439: @end example
 1440: 
 1441: If an error occurs during loading these files, Gforth terminates,
 1442: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1443: a Gforth command line.  Starting the Forth system every time gives you a
 1444: clean start every time, without interference from the results of earlier
 1445: tries.
 1446: 
 1447: I often put all the tests in a file, then load the code and run the
 1448: tests with
 1449: 
 1450: @example
 1451: gforth @var{code.fs} @var{tests.fs} -e bye
 1452: @end example
 1453: 
 1454: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1455: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1456: restart this command without ado.
 1457: 
 1458: The advantage of this approach is that the tests can be repeated easily
 1459: every time the program ist changed, making it easy to catch bugs
 1460: introduced by the change.
 1461: 
 1462: Reference: @ref{Forth source files}.
 1463: 
 1464: 
 1465: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1466: @section Comments
 1467: @cindex comments tutorial
 1468: 
 1469: @example
 1470: \ That's a comment; it ends at the end of the line
 1471: ( Another comment; it ends here: )  .s
 1472: @end example
 1473: 
 1474: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1475: separated with white space from the following text.
 1476: 
 1477: @example
 1478: \This gives an "Undefined word" error
 1479: @end example
 1480: 
 1481: The first @code{)} ends a comment started with @code{(}, so you cannot
 1482: nest @code{(}-comments; and you cannot comment out text containing a
 1483: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1484: avoid @code{)} in word names.}.
 1485: 
 1486: I use @code{\}-comments for descriptive text and for commenting out code
 1487: of one or more line; I use @code{(}-comments for describing the stack
 1488: effect, the stack contents, or for commenting out sub-line pieces of
 1489: code.
 1490: 
 1491: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1492: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1493: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1494: with @kbd{M-q}.
 1495: 
 1496: Reference: @ref{Comments}.
 1497: 
 1498: 
 1499: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1500: @section Colon Definitions
 1501: @cindex colon definitions, tutorial
 1502: @cindex definitions, tutorial
 1503: @cindex procedures, tutorial
 1504: @cindex functions, tutorial
 1505: 
 1506: are similar to procedures and functions in other programming languages.
 1507: 
 1508: @example
 1509: : squared ( n -- n^2 )
 1510:    dup * ;
 1511: 5 squared .
 1512: 7 squared .
 1513: @end example
 1514: 
 1515: @code{:} starts the colon definition; its name is @code{squared}.  The
 1516: following comment describes its stack effect.  The words @code{dup *}
 1517: are not executed, but compiled into the definition.  @code{;} ends the
 1518: colon definition.
 1519: 
 1520: The newly-defined word can be used like any other word, including using
 1521: it in other definitions:
 1522: 
 1523: @example
 1524: : cubed ( n -- n^3 )
 1525:    dup squared * ;
 1526: -5 cubed .
 1527: : fourth-power ( n -- n^4 )
 1528:    squared squared ;
 1529: 3 fourth-power .
 1530: @end example
 1531: 
 1532: @assignment
 1533: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1534: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1535: test your tests on the originals first).  Don't let the
 1536: @samp{redefined}-Messages spook you, they are just warnings.
 1537: @endassignment
 1538: 
 1539: Reference: @ref{Colon Definitions}.
 1540: 
 1541: 
 1542: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1543: @section Decompilation
 1544: @cindex decompilation tutorial
 1545: @cindex see tutorial
 1546: 
 1547: You can decompile colon definitions with @code{see}:
 1548: 
 1549: @example
 1550: see squared
 1551: see cubed
 1552: @end example
 1553: 
 1554: In Gforth @code{see} shows you a reconstruction of the source code from
 1555: the executable code.  Informations that were present in the source, but
 1556: not in the executable code, are lost (e.g., comments).
 1557: 
 1558: You can also decompile the predefined words:
 1559: 
 1560: @example
 1561: see .
 1562: see +
 1563: @end example
 1564: 
 1565: 
 1566: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1567: @section Stack-Effect Comments
 1568: @cindex stack-effect comments, tutorial
 1569: @cindex --, tutorial
 1570: By convention the comment after the name of a definition describes the
 1571: stack effect: The part in from of the @samp{--} describes the state of
 1572: the stack before the execution of the definition, i.e., the parameters
 1573: that are passed into the colon definition; the part behind the @samp{--}
 1574: is the state of the stack after the execution of the definition, i.e.,
 1575: the results of the definition.  The stack comment only shows the top
 1576: stack items that the definition accesses and/or changes.
 1577: 
 1578: You should put a correct stack effect on every definition, even if it is
 1579: just @code{( -- )}.  You should also add some descriptive comment to
 1580: more complicated words (I usually do this in the lines following
 1581: @code{:}).  If you don't do this, your code becomes unreadable (because
 1582: you have to work through every definition before you can understand
 1583: any).
 1584: 
 1585: @assignment
 1586: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1587: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1588: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1589: are done, you can compare your stack effects to those in this manual
 1590: (@pxref{Word Index}).
 1591: @endassignment
 1592: 
 1593: Sometimes programmers put comments at various places in colon
 1594: definitions that describe the contents of the stack at that place (stack
 1595: comments); i.e., they are like the first part of a stack-effect
 1596: comment. E.g.,
 1597: 
 1598: @example
 1599: : cubed ( n -- n^3 )
 1600:    dup squared  ( n n^2 ) * ;
 1601: @end example
 1602: 
 1603: In this case the stack comment is pretty superfluous, because the word
 1604: is simple enough.  If you think it would be a good idea to add such a
 1605: comment to increase readability, you should also consider factoring the
 1606: word into several simpler words (@pxref{Factoring Tutorial,,
 1607: Factoring}), which typically eliminates the need for the stack comment;
 1608: however, if you decide not to refactor it, then having such a comment is
 1609: better than not having it.
 1610: 
 1611: The names of the stack items in stack-effect and stack comments in the
 1612: standard, in this manual, and in many programs specify the type through
 1613: a type prefix, similar to Fortran and Hungarian notation.  The most
 1614: frequent prefixes are:
 1615: 
 1616: @table @code
 1617: @item n
 1618: signed integer
 1619: @item u
 1620: unsigned integer
 1621: @item c
 1622: character
 1623: @item f
 1624: Boolean flags, i.e. @code{false} or @code{true}.
 1625: @item a-addr,a-
 1626: Cell-aligned address
 1627: @item c-addr,c-
 1628: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1629: @item xt
 1630: Execution token, same size as Cell
 1631: @item w,x
 1632: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1633: 16 bits (depending on your platform and Forth system). A cell is more
 1634: commonly known as machine word, but the term @emph{word} already means
 1635: something different in Forth.
 1636: @item d
 1637: signed double-cell integer
 1638: @item ud
 1639: unsigned double-cell integer
 1640: @item r
 1641: Float (on the FP stack)
 1642: @end table
 1643: 
 1644: You can find a more complete list in @ref{Notation}.
 1645: 
 1646: @assignment
 1647: Write stack-effect comments for all definitions you have written up to
 1648: now.
 1649: @endassignment
 1650: 
 1651: 
 1652: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1653: @section Types
 1654: @cindex types tutorial
 1655: 
 1656: In Forth the names of the operations are not overloaded; so similar
 1657: operations on different types need different names; e.g., @code{+} adds
 1658: integers, and you have to use @code{f+} to add floating-point numbers.
 1659: The following prefixes are often used for related operations on
 1660: different types:
 1661: 
 1662: @table @code
 1663: @item (none)
 1664: signed integer
 1665: @item u
 1666: unsigned integer
 1667: @item c
 1668: character
 1669: @item d
 1670: signed double-cell integer
 1671: @item ud, du
 1672: unsigned double-cell integer
 1673: @item 2
 1674: two cells (not-necessarily double-cell numbers)
 1675: @item m, um
 1676: mixed single-cell and double-cell operations
 1677: @item f
 1678: floating-point (note that in stack comments @samp{f} represents flags,
 1679: and @samp{r} represents FP numbers).
 1680: @end table
 1681: 
 1682: If there are no differences between the signed and the unsigned variant
 1683: (e.g., for @code{+}), there is only the prefix-less variant.
 1684: 
 1685: Forth does not perform type checking, neither at compile time, nor at
 1686: run time.  If you use the wrong oeration, the data are interpreted
 1687: incorrectly:
 1688: 
 1689: @example
 1690: -1 u.
 1691: @end example
 1692: 
 1693: If you have only experience with type-checked languages until now, and
 1694: have heard how important type-checking is, don't panic!  In my
 1695: experience (and that of other Forthers), type errors in Forth code are
 1696: usually easy to find (once you get used to it), the increased vigilance
 1697: of the programmer tends to catch some harder errors in addition to most
 1698: type errors, and you never have to work around the type system, so in
 1699: most situations the lack of type-checking seems to be a win (projects to
 1700: add type checking to Forth have not caught on).
 1701: 
 1702: 
 1703: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1704: @section Factoring
 1705: @cindex factoring tutorial
 1706: 
 1707: If you try to write longer definitions, you will soon find it hard to
 1708: keep track of the stack contents.  Therefore, good Forth programmers
 1709: tend to write only short definitions (e.g., three lines).  The art of
 1710: finding meaningful short definitions is known as factoring (as in
 1711: factoring polynomials).
 1712: 
 1713: Well-factored programs offer additional advantages: smaller, more
 1714: general words, are easier to test and debug and can be reused more and
 1715: better than larger, specialized words.
 1716: 
 1717: So, if you run into difficulties with stack management, when writing
 1718: code, try to define meaningful factors for the word, and define the word
 1719: in terms of those.  Even if a factor contains only two words, it is
 1720: often helpful.
 1721: 
 1722: Good factoring is not easy, and it takes some practice to get the knack
 1723: for it; but even experienced Forth programmers often don't find the
 1724: right solution right away, but only when rewriting the program.  So, if
 1725: you don't come up with a good solution immediately, keep trying, don't
 1726: despair.
 1727: 
 1728: @c example !!
 1729: 
 1730: 
 1731: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1732: @section Designing the stack effect
 1733: @cindex Stack effect design, tutorial
 1734: @cindex design of stack effects, tutorial
 1735: 
 1736: In other languages you can use an arbitrary order of parameters for a
 1737: function; and since there is only one result, you don't have to deal with
 1738: the order of results, either.
 1739: 
 1740: In Forth (and other stack-based languages, e.g., PostScript) the
 1741: parameter and result order of a definition is important and should be
 1742: designed well.  The general guideline is to design the stack effect such
 1743: that the word is simple to use in most cases, even if that complicates
 1744: the implementation of the word.  Some concrete rules are:
 1745: 
 1746: @itemize @bullet
 1747: 
 1748: @item
 1749: Words consume all of their parameters (e.g., @code{.}).
 1750: 
 1751: @item
 1752: If there is a convention on the order of parameters (e.g., from
 1753: mathematics or another programming language), stick with it (e.g.,
 1754: @code{-}).
 1755: 
 1756: @item
 1757: If one parameter usually requires only a short computation (e.g., it is
 1758: a constant), pass it on the top of the stack.  Conversely, parameters
 1759: that usually require a long sequence of code to compute should be passed
 1760: as the bottom (i.e., first) parameter.  This makes the code easier to
 1761: read, because reader does not need to keep track of the bottom item
 1762: through a long sequence of code (or, alternatively, through stack
 1763: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1764: address on top of the stack because it is usually simpler to compute
 1765: than the stored value (often the address is just a variable).
 1766: 
 1767: @item
 1768: Similarly, results that are usually consumed quickly should be returned
 1769: on the top of stack, whereas a result that is often used in long
 1770: computations should be passed as bottom result.  E.g., the file words
 1771: like @code{open-file} return the error code on the top of stack, because
 1772: it is usually consumed quickly by @code{throw}; moreover, the error code
 1773: has to be checked before doing anything with the other results.
 1774: 
 1775: @end itemize
 1776: 
 1777: These rules are just general guidelines, don't lose sight of the overall
 1778: goal to make the words easy to use.  E.g., if the convention rule
 1779: conflicts with the computation-length rule, you might decide in favour
 1780: of the convention if the word will be used rarely, and in favour of the
 1781: computation-length rule if the word will be used frequently (because
 1782: with frequent use the cost of breaking the computation-length rule would
 1783: be quite high, and frequent use makes it easier to remember an
 1784: unconventional order).
 1785: 
 1786: @c example !! structure package
 1787: 
 1788: 
 1789: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1790: @section Local Variables
 1791: @cindex local variables, tutorial
 1792: 
 1793: You can define local variables (@emph{locals}) in a colon definition:
 1794: 
 1795: @example
 1796: : swap @{ a b -- b a @}
 1797:   b a ;
 1798: 1 2 swap .s 2drop
 1799: @end example
 1800: 
 1801: (If your Forth system does not support this syntax, include
 1802: @file{compat/anslocals.fs} first).
 1803: 
 1804: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1805: takes two cells from the stack, puts the top of stack in @code{b} and
 1806: the next stack element in @code{a}.  @code{--} starts a comment ending
 1807: with @code{@}}.  After the locals definition, using the name of the
 1808: local will push its value on the stack.  You can leave the comment
 1809: part (@code{-- b a}) away:
 1810: 
 1811: @example
 1812: : swap ( x1 x2 -- x2 x1 )
 1813:   @{ a b @} b a ;
 1814: @end example
 1815: 
 1816: In Gforth you can have several locals definitions, anywhere in a colon
 1817: definition; in contrast, in a standard program you can have only one
 1818: locals definition per colon definition, and that locals definition must
 1819: be outside any controll structure.
 1820: 
 1821: With locals you can write slightly longer definitions without running
 1822: into stack trouble.  However, I recommend trying to write colon
 1823: definitions without locals for exercise purposes to help you gain the
 1824: essential factoring skills.
 1825: 
 1826: @assignment
 1827: Rewrite your definitions until now with locals
 1828: @endassignment
 1829: 
 1830: Reference: @ref{Locals}.
 1831: 
 1832: 
 1833: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1834: @section Conditional execution
 1835: @cindex conditionals, tutorial
 1836: @cindex if, tutorial
 1837: 
 1838: In Forth you can use control structures only inside colon definitions.
 1839: An @code{if}-structure looks like this:
 1840: 
 1841: @example
 1842: : abs ( n1 -- +n2 )
 1843:     dup 0 < if
 1844:         negate
 1845:     endif ;
 1846: 5 abs .
 1847: -5 abs .
 1848: @end example
 1849: 
 1850: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1851: the following code is performed, otherwise execution continues after the
 1852: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1853: elements and prioduces a flag:
 1854: 
 1855: @example
 1856: 1 2 < .
 1857: 2 1 < .
 1858: 1 1 < .
 1859: @end example
 1860: 
 1861: Actually the standard name for @code{endif} is @code{then}.  This
 1862: tutorial presents the examples using @code{endif}, because this is often
 1863: less confusing for people familiar with other programming languages
 1864: where @code{then} has a different meaning.  If your system does not have
 1865: @code{endif}, define it with
 1866: 
 1867: @example
 1868: : endif postpone then ; immediate
 1869: @end example
 1870: 
 1871: You can optionally use an @code{else}-part:
 1872: 
 1873: @example
 1874: : min ( n1 n2 -- n )
 1875:   2dup < if
 1876:     drop
 1877:   else
 1878:     nip
 1879:   endif ;
 1880: 2 3 min .
 1881: 3 2 min .
 1882: @end example
 1883: 
 1884: @assignment
 1885: Write @code{min} without @code{else}-part (hint: what's the definition
 1886: of @code{nip}?).
 1887: @endassignment
 1888: 
 1889: Reference: @ref{Selection}.
 1890: 
 1891: 
 1892: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1893: @section Flags and Comparisons
 1894: @cindex flags tutorial
 1895: @cindex comparison tutorial
 1896: 
 1897: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1898: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1899: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1900: treated as true flag.
 1901: 
 1902: @example
 1903: false .
 1904: true .
 1905: true hex u. decimal
 1906: @end example
 1907: 
 1908: Comparison words produce canonical flags:
 1909: 
 1910: @example
 1911: 1 1 = .
 1912: 1 0= .
 1913: 0 1 < .
 1914: 0 0 < .
 1915: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1916: -1 1 < .
 1917: @end example
 1918: 
 1919: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1920: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 1921: these combinations are standard (for details see the standard,
 1922: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 1923: 
 1924: You can use @code{and or xor invert} can be used as operations on
 1925: canonical flags.  Actually they are bitwise operations:
 1926: 
 1927: @example
 1928: 1 2 and .
 1929: 1 2 or .
 1930: 1 3 xor .
 1931: 1 invert .
 1932: @end example
 1933: 
 1934: You can convert a zero/non-zero flag into a canonical flag with
 1935: @code{0<>} (and complement it on the way with @code{0=}).
 1936: 
 1937: @example
 1938: 1 0= .
 1939: 1 0<> .
 1940: @end example
 1941: 
 1942: You can use the all-bits-set feature of canonical flags and the bitwise
 1943: operation of the Boolean operations to avoid @code{if}s:
 1944: 
 1945: @example
 1946: : foo ( n1 -- n2 )
 1947:   0= if
 1948:     14
 1949:   else
 1950:     0
 1951:   endif ;
 1952: 0 foo .
 1953: 1 foo .
 1954: 
 1955: : foo ( n1 -- n2 )
 1956:   0= 14 and ;
 1957: 0 foo .
 1958: 1 foo .
 1959: @end example
 1960: 
 1961: @assignment
 1962: Write @code{min} without @code{if}.
 1963: @endassignment
 1964: 
 1965: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 1966: @ref{Bitwise operations}.
 1967: 
 1968: 
 1969: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 1970: @section General Loops
 1971: @cindex loops, indefinite, tutorial
 1972: 
 1973: The endless loop is the most simple one:
 1974: 
 1975: @example
 1976: : endless ( -- )
 1977:   0 begin
 1978:     dup . 1+
 1979:   again ;
 1980: endless
 1981: @end example
 1982: 
 1983: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 1984: does nothing at run-time, @code{again} jumps back to @code{begin}.
 1985: 
 1986: A loop with one exit at any place looks like this:
 1987: 
 1988: @example
 1989: : log2 ( +n1 -- n2 )
 1990: \ logarithmus dualis of n1>0, rounded down to the next integer
 1991:   assert( dup 0> )
 1992:   2/ 0 begin
 1993:     over 0> while
 1994:       1+ swap 2/ swap
 1995:   repeat
 1996:   nip ;
 1997: 7 log2 .
 1998: 8 log2 .
 1999: @end example
 2000: 
 2001: At run-time @code{while} consumes a flag; if it is 0, execution
 2002: continues behind the @code{repeat}; if the flag is non-zero, execution
 2003: continues behind the @code{while}.  @code{Repeat} jumps back to
 2004: @code{begin}, just like @code{again}.
 2005: 
 2006: In Forth there are many combinations/abbreviations, like @code{1+}.
 2007: However, @code{2/} is not one of them; it shifts its argument right by
 2008: one bit (arithmetic shift right):
 2009: 
 2010: @example
 2011: -5 2 / .
 2012: -5 2/ .
 2013: @end example
 2014: 
 2015: @code{assert(} is no standard word, but you can get it on systems other
 2016: then Gforth by including @file{compat/assert.fs}.  You can see what it
 2017: does by trying
 2018: 
 2019: @example
 2020: 0 log2 .
 2021: @end example
 2022: 
 2023: Here's a loop with an exit at the end:
 2024: 
 2025: @example
 2026: : log2 ( +n1 -- n2 )
 2027: \ logarithmus dualis of n1>0, rounded down to the next integer
 2028:   assert( dup 0 > )
 2029:   -1 begin
 2030:     1+ swap 2/ swap
 2031:     over 0 <=
 2032:   until
 2033:   nip ;
 2034: @end example
 2035: 
 2036: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2037: the @code{begin}, otherwise after the @code{until}.
 2038: 
 2039: @assignment
 2040: Write a definition for computing the greatest common divisor.
 2041: @endassignment
 2042: 
 2043: Reference: @ref{Simple Loops}.
 2044: 
 2045: 
 2046: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2047: @section Counted loops
 2048: @cindex loops, counted, tutorial
 2049: 
 2050: @example
 2051: : ^ ( n1 u -- n )
 2052: \ n = the uth power of u1
 2053:   1 swap 0 u+do
 2054:     over *
 2055:   loop
 2056:   nip ;
 2057: 3 2 ^ .
 2058: 4 3 ^ .
 2059: @end example
 2060: 
 2061: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2062: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2063: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2064: times (or not at all, if @code{u3-u4<0}).
 2065: 
 2066: You can see the stack effect design rules at work in the stack effect of
 2067: the loop start words: Since the start value of the loop is more
 2068: frequently constant than the end value, the start value is passed on
 2069: the top-of-stack.
 2070: 
 2071: You can access the counter of a counted loop with @code{i}:
 2072: 
 2073: @example
 2074: : fac ( u -- u! )
 2075:   1 swap 1+ 1 u+do
 2076:     i *
 2077:   loop ;
 2078: 5 fac .
 2079: 7 fac .
 2080: @end example
 2081: 
 2082: There is also @code{+do}, which expects signed numbers (important for
 2083: deciding whether to enter the loop).
 2084: 
 2085: @assignment
 2086: Write a definition for computing the nth Fibonacci number.
 2087: @endassignment
 2088: 
 2089: You can also use increments other than 1:
 2090: 
 2091: @example
 2092: : up2 ( n1 n2 -- )
 2093:   +do
 2094:     i .
 2095:   2 +loop ;
 2096: 10 0 up2
 2097: 
 2098: : down2 ( n1 n2 -- )
 2099:   -do
 2100:     i .
 2101:   2 -loop ;
 2102: 0 10 down2
 2103: @end example
 2104: 
 2105: Reference: @ref{Counted Loops}.
 2106: 
 2107: 
 2108: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2109: @section Recursion
 2110: @cindex recursion tutorial
 2111: 
 2112: Usually the name of a definition is not visible in the definition; but
 2113: earlier definitions are usually visible:
 2114: 
 2115: @example
 2116: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
 2117: : / ( n1 n2 -- n )
 2118:   dup 0= if
 2119:     -10 throw \ report division by zero
 2120:   endif
 2121:   /           \ old version
 2122: ;
 2123: 1 0 /
 2124: @end example
 2125: 
 2126: For recursive definitions you can use @code{recursive} (non-standard) or
 2127: @code{recurse}:
 2128: 
 2129: @example
 2130: : fac1 ( n -- n! ) recursive
 2131:  dup 0> if
 2132:    dup 1- fac1 *
 2133:  else
 2134:    drop 1
 2135:  endif ;
 2136: 7 fac1 .
 2137: 
 2138: : fac2 ( n -- n! )
 2139:  dup 0> if
 2140:    dup 1- recurse *
 2141:  else
 2142:    drop 1
 2143:  endif ;
 2144: 8 fac2 .
 2145: @end example
 2146: 
 2147: @assignment
 2148: Write a recursive definition for computing the nth Fibonacci number.
 2149: @endassignment
 2150: 
 2151: Reference (including indirect recursion): @xref{Calls and returns}.
 2152: 
 2153: 
 2154: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2155: @section Leaving definitions or loops
 2156: @cindex leaving definitions, tutorial
 2157: @cindex leaving loops, tutorial
 2158: 
 2159: @code{EXIT} exits the current definition right away.  For every counted
 2160: loop that is left in this way, an @code{UNLOOP} has to be performed
 2161: before the @code{EXIT}:
 2162: 
 2163: @c !! real examples
 2164: @example
 2165: : ...
 2166:  ... u+do
 2167:    ... if
 2168:      ... unloop exit
 2169:    endif
 2170:    ...
 2171:  loop
 2172:  ... ;
 2173: @end example
 2174: 
 2175: @code{LEAVE} leaves the innermost counted loop right away:
 2176: 
 2177: @example
 2178: : ...
 2179:  ... u+do
 2180:    ... if
 2181:      ... leave
 2182:    endif
 2183:    ...
 2184:  loop
 2185:  ... ;
 2186: @end example
 2187: 
 2188: @c !! example
 2189: 
 2190: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2191: 
 2192: 
 2193: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2194: @section Return Stack
 2195: @cindex return stack tutorial
 2196: 
 2197: In addition to the data stack Forth also has a second stack, the return
 2198: stack; most Forth systems store the return addresses of procedure calls
 2199: there (thus its name).  Programmers can also use this stack:
 2200: 
 2201: @example
 2202: : foo ( n1 n2 -- )
 2203:  .s
 2204:  >r .s
 2205:  r@@ .
 2206:  >r .s
 2207:  r@@ .
 2208:  r> .
 2209:  r@@ .
 2210:  r> . ;
 2211: 1 2 foo
 2212: @end example
 2213: 
 2214: @code{>r} takes an element from the data stack and pushes it onto the
 2215: return stack; conversely, @code{r>} moves an elementm from the return to
 2216: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2217: on the return stack.
 2218: 
 2219: Forth programmers usually use the return stack for storing data
 2220: temporarily, if using the data stack alone would be too complex, and
 2221: factoring and locals are not an option:
 2222: 
 2223: @example
 2224: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2225:  rot >r rot r> ;
 2226: @end example
 2227: 
 2228: The return address of the definition and the loop control parameters of
 2229: counted loops usually reside on the return stack, so you have to take
 2230: all items, that you have pushed on the return stack in a colon
 2231: definition or counted loop, from the return stack before the definition
 2232: or loop ends.  You cannot access items that you pushed on the return
 2233: stack outside some definition or loop within the definition of loop.
 2234: 
 2235: If you miscount the return stack items, this usually ends in a crash:
 2236: 
 2237: @example
 2238: : crash ( n -- )
 2239:   >r ;
 2240: 5 crash
 2241: @end example
 2242: 
 2243: You cannot mix using locals and using the return stack (according to the
 2244: standard; Gforth has no problem).  However, they solve the same
 2245: problems, so this shouldn't be an issue.
 2246: 
 2247: @assignment
 2248: Can you rewrite any of the definitions you wrote until now in a better
 2249: way using the return stack?
 2250: @endassignment
 2251: 
 2252: Reference: @ref{Return stack}.
 2253: 
 2254: 
 2255: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2256: @section Memory
 2257: @cindex memory access/allocation tutorial
 2258: 
 2259: You can create a global variable @code{v} with
 2260: 
 2261: @example
 2262: variable v ( -- addr )
 2263: @end example
 2264: 
 2265: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2266: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2267: values into this cell and @code{@@} (fetch) to load the value from the
 2268: stack into memory:
 2269: 
 2270: @example
 2271: v .
 2272: 5 v ! .s
 2273: v @@ .
 2274: @end example
 2275: 
 2276: You can see a raw dump of memory with @code{dump}:
 2277: 
 2278: @example
 2279: v 1 cells .s dump
 2280: @end example
 2281: 
 2282: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2283: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2284: also reserve more memory:
 2285: 
 2286: @example
 2287: create v2 20 cells allot
 2288: v2 20 cells dump
 2289: @end example
 2290: 
 2291: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2292: address pushed by @code{v2} points to the start of these 20 cells.  You
 2293: can use address arithmetic to access these cells:
 2294: 
 2295: @example
 2296: 3 v2 5 cells + !
 2297: v2 20 cells dump
 2298: @end example
 2299: 
 2300: You can reserve and initialize memory with @code{,}:
 2301: 
 2302: @example
 2303: create v3
 2304:   5 , 4 , 3 , 2 , 1 ,
 2305: v3 @@ .
 2306: v3 cell+ @@ .
 2307: v3 2 cells + @@ .
 2308: v3 5 cells dump
 2309: @end example
 2310: 
 2311: @assignment
 2312: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2313: @code{u} cells, with the first of these cells at @code{addr}, the next
 2314: one at @code{addr cell+} etc.
 2315: @endassignment
 2316: 
 2317: You can also reserve memory without creating a new word:
 2318: 
 2319: @example
 2320: here 10 cells allot .
 2321: here .
 2322: @end example
 2323: 
 2324: @code{Here} pushes the start address of the memory area.  You should
 2325: store it somewhere, or you will have a hard time finding the memory area
 2326: again.
 2327: 
 2328: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2329: the system's data structures for words etc. on Gforth and most other
 2330: Forth systems.  It is managed like a stack: You can free the memory that
 2331: you have just @code{allot}ed with
 2332: 
 2333: @example
 2334: -10 cells allot
 2335: here .
 2336: @end example
 2337: 
 2338: Note that you cannot do this if you have created a new word in the
 2339: meantime (because then your @code{allot}ed memory is no longer on the
 2340: top of the dictionary ``stack'').
 2341: 
 2342: Alternatively, you can use @code{allocate} and @code{free} which allow
 2343: freeing memory in any order:
 2344: 
 2345: @example
 2346: 10 cells allocate throw .s
 2347: 20 cells allocate throw .s
 2348: swap
 2349: free throw
 2350: free throw
 2351: @end example
 2352: 
 2353: The @code{throw}s deal with errors (e.g., out of memory).
 2354: 
 2355: And there is also a
 2356: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2357: garbage collector}, which eliminates the need to @code{free} memory
 2358: explicitly.
 2359: 
 2360: Reference: @ref{Memory}.
 2361: 
 2362: 
 2363: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2364: @section Characters and Strings
 2365: @cindex strings tutorial
 2366: @cindex characters tutorial
 2367: 
 2368: On the stack characters take up a cell, like numbers.  In memory they
 2369: have their own size (one 8-bit byte on most systems), and therefore
 2370: require their own words for memory access:
 2371: 
 2372: @example
 2373: create v4 
 2374:   104 c, 97 c, 108 c, 108 c, 111 c,
 2375: v4 4 chars + c@@ .
 2376: v4 5 chars dump
 2377: @end example
 2378: 
 2379: The preferred representation of strings on the stack is @code{addr
 2380: u-count}, where @code{addr} is the address of the first character and
 2381: @code{u-count} is the number of characters in the string.
 2382: 
 2383: @example
 2384: v4 5 type
 2385: @end example
 2386: 
 2387: You get a string constant with
 2388: 
 2389: @example
 2390: s" hello, world" .s
 2391: type
 2392: @end example
 2393: 
 2394: Make sure you have a space between @code{s"} and the string; @code{s"}
 2395: is a normal Forth word and must be delimited with white space (try what
 2396: happens when you remove the space).
 2397: 
 2398: However, this interpretive use of @code{s"} is quite restricted: the
 2399: string exists only until the next call of @code{s"} (some Forth systems
 2400: keep more than one of these strings, but usually they still have a
 2401: limited lifetime).
 2402: 
 2403: @example
 2404: s" hello," s" world" .s
 2405: type
 2406: type
 2407: @end example
 2408: 
 2409: You can also use @code{s"} in a definition, and the resulting
 2410: strings then live forever (well, for as long as the definition):
 2411: 
 2412: @example
 2413: : foo s" hello," s" world" ;
 2414: foo .s
 2415: type
 2416: type
 2417: @end example
 2418: 
 2419: @assignment
 2420: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2421: Implement @code{type ( addr u -- )}.
 2422: @endassignment
 2423: 
 2424: Reference: @ref{Memory Blocks}.
 2425: 
 2426: 
 2427: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
 2428: @section Alignment
 2429: @cindex alignment tutorial
 2430: @cindex memory alignment tutorial
 2431: 
 2432: On many processors cells have to be aligned in memory, if you want to
 2433: access them with @code{@@} and @code{!} (and even if the processor does
 2434: not require alignment, access to aligned cells is faster).
 2435: 
 2436: @code{Create} aligns @code{here} (i.e., the place where the next
 2437: allocation will occur, and that the @code{create}d word points to).
 2438: Likewise, the memory produced by @code{allocate} starts at an aligned
 2439: address.  Adding a number of @code{cells} to an aligned address produces
 2440: another aligned address.
 2441: 
 2442: However, address arithmetic involving @code{char+} and @code{chars} can
 2443: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2444: a-addr )} produces the next aligned address:
 2445: 
 2446: @example
 2447: v3 char+ aligned .s @@ .
 2448: v3 char+ .s @@ .
 2449: @end example
 2450: 
 2451: Similarly, @code{align} advances @code{here} to the next aligned
 2452: address:
 2453: 
 2454: @example
 2455: create v5 97 c,
 2456: here .
 2457: align here .
 2458: 1000 ,
 2459: @end example
 2460: 
 2461: Note that you should use aligned addresses even if your processor does
 2462: not require them, if you want your program to be portable.
 2463: 
 2464: Reference: @ref{Address arithmetic}.
 2465: 
 2466: 
 2467: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
 2468: @section Files
 2469: @cindex files tutorial
 2470: 
 2471: This section gives a short introduction into how to use files inside
 2472: Forth. It's broken up into five easy steps:
 2473: 
 2474: @enumerate 1
 2475: @item Opened an ASCII text file for input
 2476: @item Opened a file for output
 2477: @item Read input file until string matched (or some other condition matched)
 2478: @item Wrote some lines from input ( modified or not) to output
 2479: @item Closed the files.
 2480: @end enumerate
 2481: 
 2482: @subsection Open file for input
 2483: 
 2484: @example
 2485: s" foo.in"  r/o open-file throw Value fd-in
 2486: @end example
 2487: 
 2488: @subsection Create file for output
 2489: 
 2490: @example
 2491: s" foo.out" w/o create-file throw Value fd-out
 2492: @end example
 2493: 
 2494: The available file modes are r/o for read-only access, r/w for
 2495: read-write access, and w/o for write-only access. You could open both
 2496: files with r/w, too, if you like. All file words return error codes; for
 2497: most applications, it's best to pass there error codes with @code{throw}
 2498: to the outer error handler.
 2499: 
 2500: If you want words for opening and assigning, define them as follows:
 2501: 
 2502: @example
 2503: 0 Value fd-in
 2504: 0 Value fd-out
 2505: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2506: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2507: @end example
 2508: 
 2509: Usage example:
 2510: 
 2511: @example
 2512: s" foo.in" open-input
 2513: s" foo.out" open-output
 2514: @end example
 2515: 
 2516: @subsection Scan file for a particular line
 2517: 
 2518: @example
 2519: 256 Constant max-line
 2520: Create line-buffer  max-line 2 + allot
 2521: 
 2522: : scan-file ( addr u -- )
 2523:   begin
 2524:       line-buffer max-line fd-in read-line throw
 2525:   while
 2526:          >r 2dup line-buffer r> compare 0=
 2527:      until
 2528:   else
 2529:      drop
 2530:   then
 2531:   2drop ;
 2532: @end example
 2533: 
 2534: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2535: the buffer at addr, and returns the number of bytes read, a flag that is
 2536: false when the end of file is reached, and an error code.
 2537: 
 2538: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2539: returns zero if both strings are equal. It returns a positive number if
 2540: the first string is lexically greater, a negative if the second string
 2541: is lexically greater.
 2542: 
 2543: We haven't seen this loop here; it has two exits. Since the @code{while}
 2544: exits with the number of bytes read on the stack, we have to clean up
 2545: that separately; that's after the @code{else}.
 2546: 
 2547: Usage example:
 2548: 
 2549: @example
 2550: s" The text I search is here" scan-file
 2551: @end example
 2552: 
 2553: @subsection Copy input to output
 2554: 
 2555: @example
 2556: : copy-file ( -- )
 2557:   begin
 2558:       line-buffer max-line fd-in read-line throw
 2559:   while
 2560:       line-buffer swap fd-out write-file throw
 2561:   repeat ;
 2562: @end example
 2563: 
 2564: @subsection Close files
 2565: 
 2566: @example
 2567: fd-in close-file throw
 2568: fd-out close-file throw
 2569: @end example
 2570: 
 2571: Likewise, you can put that into definitions, too:
 2572: 
 2573: @example
 2574: : close-input ( -- )  fd-in close-file throw ;
 2575: : close-output ( -- )  fd-out close-file throw ;
 2576: @end example
 2577: 
 2578: @assignment
 2579: How could you modify @code{copy-file} so that it copies until a second line is
 2580: matched? Can you write a program that extracts a section of a text file,
 2581: given the line that starts and the line that terminates that section?
 2582: @endassignment
 2583: 
 2584: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2585: @section Interpretation and Compilation Semantics and Immediacy
 2586: @cindex semantics tutorial
 2587: @cindex interpretation semantics tutorial
 2588: @cindex compilation semantics tutorial
 2589: @cindex immediate, tutorial
 2590: 
 2591: When a word is compiled, it behaves differently from being interpreted.
 2592: E.g., consider @code{+}:
 2593: 
 2594: @example
 2595: 1 2 + .
 2596: : foo + ;
 2597: @end example
 2598: 
 2599: These two behaviours are known as compilation and interpretation
 2600: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2601: is to append the interpretation semantics to the currently defined word
 2602: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2603: later, the interpretation semantics of @code{+} (i.e., adding two
 2604: numbers) will be performed.
 2605: 
 2606: However, there are words with non-default compilation semantics, e.g.,
 2607: the control-flow words like @code{if}.  You can use @code{immediate} to
 2608: change the compilation semantics of the last defined word to be equal to
 2609: the interpretation semantics:
 2610: 
 2611: @example
 2612: : [FOO] ( -- )
 2613:  5 . ; immediate
 2614: 
 2615: [FOO]
 2616: : bar ( -- )
 2617:   [FOO] ;
 2618: bar
 2619: see bar
 2620: @end example
 2621: 
 2622: Two conventions to mark words with non-default compilation semnatics are
 2623: names with brackets (more frequently used) and to write them all in
 2624: upper case (less frequently used).
 2625: 
 2626: In Gforth (and many other systems) you can also remove the
 2627: interpretation semantics with @code{compile-only} (the compilation
 2628: semantics is derived from the original interpretation semantics):
 2629: 
 2630: @example
 2631: : flip ( -- )
 2632:  6 . ; compile-only \ but not immediate
 2633: flip
 2634: 
 2635: : flop ( -- )
 2636:  flip ;
 2637: flop
 2638: @end example
 2639: 
 2640: In this example the interpretation semantics of @code{flop} is equal to
 2641: the original interpretation semantics of @code{flip}.
 2642: 
 2643: The text interpreter has two states: in interpret state, it performs the
 2644: interpretation semantics of words it encounters; in compile state, it
 2645: performs the compilation semantics of these words.
 2646: 
 2647: Among other things, @code{:} switches into compile state, and @code{;}
 2648: switches back to interpret state.  They contain the factors @code{]}
 2649: (switch to compile state) and @code{[} (switch to interpret state), that
 2650: do nothing but switch the state.
 2651: 
 2652: @example
 2653: : xxx ( -- )
 2654:   [ 5 . ]
 2655: ;
 2656: 
 2657: xxx
 2658: see xxx
 2659: @end example
 2660: 
 2661: These brackets are also the source of the naming convention mentioned
 2662: above.
 2663: 
 2664: Reference: @ref{Interpretation and Compilation Semantics}.
 2665: 
 2666: 
 2667: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2668: @section Execution Tokens
 2669: @cindex execution tokens tutorial
 2670: @cindex XT tutorial
 2671: 
 2672: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2673: cell representing the interpretation semantics of a word.  You can
 2674: execute this semantics with @code{execute}:
 2675: 
 2676: @example
 2677: ' + .s
 2678: 1 2 rot execute .
 2679: @end example
 2680: 
 2681: The XT is similar to a function pointer in C.  However, parameter
 2682: passing through the stack makes it a little more flexible:
 2683: 
 2684: @example
 2685: : map-array ( ... addr u xt -- ... )
 2686: \ executes xt ( ... x -- ... ) for every element of the array starting
 2687: \ at addr and containing u elements
 2688:   @{ xt @}
 2689:   cells over + swap ?do
 2690:     i @@ xt execute
 2691:   1 cells +loop ;
 2692: 
 2693: create a 3 , 4 , 2 , -1 , 4 ,
 2694: a 5 ' . map-array .s
 2695: 0 a 5 ' + map-array .
 2696: s" max-n" environment? drop .s
 2697: a 5 ' min map-array .
 2698: @end example
 2699: 
 2700: You can use map-array with the XTs of words that consume one element
 2701: more than they produce.  In theory you can also use it with other XTs,
 2702: but the stack effect then depends on the size of the array, which is
 2703: hard to understand.
 2704: 
 2705: Since XTs are cell-sized, you can store them in memory and manipulate
 2706: them on the stack like other cells.  You can also compile the XT into a
 2707: word with @code{compile,}:
 2708: 
 2709: @example
 2710: : foo1 ( n1 n2 -- n )
 2711:    [ ' + compile, ] ;
 2712: see foo
 2713: @end example
 2714: 
 2715: This is non-standard, because @code{compile,} has no compilation
 2716: semantics in the standard, but it works in good Forth systems.  For the
 2717: broken ones, use
 2718: 
 2719: @example
 2720: : [compile,] compile, ; immediate
 2721: 
 2722: : foo1 ( n1 n2 -- n )
 2723:    [ ' + ] [compile,] ;
 2724: see foo
 2725: @end example
 2726: 
 2727: @code{'} is a word with default compilation semantics; it parses the
 2728: next word when its interpretation semantics are executed, not during
 2729: compilation:
 2730: 
 2731: @example
 2732: : foo ( -- xt )
 2733:   ' ;
 2734: see foo
 2735: : bar ( ... "word" -- ... )
 2736:   ' execute ;
 2737: see bar
 2738: 1 2 bar + .
 2739: @end example
 2740: 
 2741: You often want to parse a word during compilation and compile its XT so
 2742: it will be pushed on the stack at run-time.  @code{[']} does this:
 2743: 
 2744: @example
 2745: : xt-+ ( -- xt )
 2746:   ['] + ;
 2747: see xt-+
 2748: 1 2 xt-+ execute .
 2749: @end example
 2750: 
 2751: Many programmers tend to see @code{'} and the word it parses as one
 2752: unit, and expect it to behave like @code{[']} when compiled, and are
 2753: confused by the actual behaviour.  If you are, just remember that the
 2754: Forth system just takes @code{'} as one unit and has no idea that it is
 2755: a parsing word (attempts to convenience programmers in this issue have
 2756: usually resulted in even worse pitfalls, see
 2757: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2758: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2759: 
 2760: Note that the state of the interpreter does not come into play when
 2761: creating and executing XTs.  I.e., even when you execute @code{'} in
 2762: compile state, it still gives you the interpretation semantics.  And
 2763: whatever that state is, @code{execute} performs the semantics
 2764: represented by the XT (i.e., for XTs produced with @code{'} the
 2765: interpretation semantics).
 2766: 
 2767: Reference: @ref{Tokens for Words}.
 2768: 
 2769: 
 2770: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2771: @section Exceptions
 2772: @cindex exceptions tutorial
 2773: 
 2774: @code{throw ( n -- )} causes an exception unless n is zero.
 2775: 
 2776: @example
 2777: 100 throw .s
 2778: 0 throw .s
 2779: @end example
 2780: 
 2781: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2782: it catches exceptions and pushes the number of the exception on the
 2783: stack (or 0, if the xt executed without exception).  If there was an
 2784: exception, the stacks have the same depth as when entering @code{catch}:
 2785: 
 2786: @example
 2787: .s
 2788: 3 0 ' / catch .s
 2789: 3 2 ' / catch .s
 2790: @end example
 2791: 
 2792: @assignment
 2793: Try the same with @code{execute} instead of @code{catch}.
 2794: @endassignment
 2795: 
 2796: @code{Throw} always jumps to the dynamically next enclosing
 2797: @code{catch}, even if it has to leave several call levels to achieve
 2798: this:
 2799: 
 2800: @example
 2801: : foo 100 throw ;
 2802: : foo1 foo ." after foo" ;
 2803: : bar ['] foo1 catch ;
 2804: bar .
 2805: @end example
 2806: 
 2807: It is often important to restore a value upon leaving a definition, even
 2808: if the definition is left through an exception.  You can ensure this
 2809: like this:
 2810: 
 2811: @example
 2812: : ...
 2813:    save-x
 2814:    ['] word-changing-x catch ( ... n )
 2815:    restore-x
 2816:    ( ... n ) throw ;
 2817: @end example
 2818: 
 2819: Gforth provides an alternative syntax in addition to @code{catch}:
 2820: @code{try ... recover ... endtry}.  If the code between @code{try} and
 2821: @code{recover} has an exception, the stack depths are restored, the
 2822: exception number is pushed on the stack, and the code between
 2823: @code{recover} and @code{endtry} is performed.  E.g., the definition for
 2824: @code{catch} is
 2825: 
 2826: @example
 2827: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
 2828:   try
 2829:     execute 0
 2830:   recover
 2831:     nip
 2832:   endtry ;
 2833: @end example
 2834: 
 2835: The equivalent to the restoration code above is
 2836: 
 2837: @example
 2838: : ...
 2839:   save-x
 2840:   try
 2841:     word-changing-x 0
 2842:   recover endtry
 2843:   restore-x
 2844:   throw ;
 2845: @end example
 2846: 
 2847: This works if @code{word-changing-x} does not change the stack depth,
 2848: otherwise you should add some code between @code{recover} and
 2849: @code{endtry} to balance the stack.
 2850: 
 2851: Reference: @ref{Exception Handling}.
 2852: 
 2853: 
 2854: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2855: @section Defining Words
 2856: @cindex defining words tutorial
 2857: @cindex does> tutorial
 2858: @cindex create...does> tutorial
 2859: 
 2860: @c before semantics?
 2861: 
 2862: @code{:}, @code{create}, and @code{variable} are definition words: They
 2863: define other words.  @code{Constant} is another definition word:
 2864: 
 2865: @example
 2866: 5 constant foo
 2867: foo .
 2868: @end example
 2869: 
 2870: You can also use the prefixes @code{2} (double-cell) and @code{f}
 2871: (floating point) with @code{variable} and @code{constant}.
 2872: 
 2873: You can also define your own defining words.  E.g.:
 2874: 
 2875: @example
 2876: : variable ( "name" -- )
 2877:   create 0 , ;
 2878: @end example
 2879: 
 2880: You can also define defining words that create words that do something
 2881: other than just producing their address:
 2882: 
 2883: @example
 2884: : constant ( n "name" -- )
 2885:   create ,
 2886: does> ( -- n )
 2887:   ( addr ) @@ ;
 2888: 
 2889: 5 constant foo
 2890: foo .
 2891: @end example
 2892: 
 2893: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 2894: @code{does>} replaces @code{;}, but it also does something else: It
 2895: changes the last defined word such that it pushes the address of the
 2896: body of the word and then performs the code after the @code{does>}
 2897: whenever it is called.
 2898: 
 2899: In the example above, @code{constant} uses @code{,} to store 5 into the
 2900: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 2901: the body onto the stack, then (in the code after the @code{does>})
 2902: fetches the 5 from there.
 2903: 
 2904: The stack comment near the @code{does>} reflects the stack effect of the
 2905: defined word, not the stack effect of the code after the @code{does>}
 2906: (the difference is that the code expects the address of the body that
 2907: the stack comment does not show).
 2908: 
 2909: You can use these definition words to do factoring in cases that involve
 2910: (other) definition words.  E.g., a field offset is always added to an
 2911: address.  Instead of defining
 2912: 
 2913: @example
 2914: 2 cells constant offset-field1
 2915: @end example
 2916: 
 2917: and using this like
 2918: 
 2919: @example
 2920: ( addr ) offset-field1 +
 2921: @end example
 2922: 
 2923: you can define a definition word
 2924: 
 2925: @example
 2926: : simple-field ( n "name" -- )
 2927:   create ,
 2928: does> ( n1 -- n1+n )
 2929:   ( addr ) @@ + ;
 2930: @end example
 2931: 
 2932: Definition and use of field offsets now look like this:
 2933: 
 2934: @example
 2935: 2 cells simple-field field1
 2936: create mystruct 4 cells allot
 2937: mystruct .s field1 .s drop
 2938: @end example
 2939: 
 2940: If you want to do something with the word without performing the code
 2941: after the @code{does>}, you can access the body of a @code{create}d word
 2942: with @code{>body ( xt -- addr )}:
 2943: 
 2944: @example
 2945: : value ( n "name" -- )
 2946:   create ,
 2947: does> ( -- n1 )
 2948:   @@ ;
 2949: : to ( n "name" -- )
 2950:   ' >body ! ;
 2951: 
 2952: 5 value foo
 2953: foo .
 2954: 7 to foo
 2955: foo .
 2956: @end example
 2957: 
 2958: @assignment
 2959: Define @code{defer ( "name" -- )}, which creates a word that stores an
 2960: XT (at the start the XT of @code{abort}), and upon execution
 2961: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 2962: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 2963: recursion is one application of @code{defer}.
 2964: @endassignment
 2965: 
 2966: Reference: @ref{User-defined Defining Words}.
 2967: 
 2968: 
 2969: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 2970: @section Arrays and Records
 2971: @cindex arrays tutorial
 2972: @cindex records tutorial
 2973: @cindex structs tutorial
 2974: 
 2975: Forth has no standard words for defining data structures such as arrays
 2976: and records (structs in C terminology), but you can build them yourself
 2977: based on address arithmetic.  You can also define words for defining
 2978: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 2979: 
 2980: One of the first projects a Forth newcomer sets out upon when learning
 2981: about defining words is an array defining word (possibly for
 2982: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 2983: learn something from it.  However, don't be disappointed when you later
 2984: learn that you have little use for these words (inappropriate use would
 2985: be even worse).  I have not yet found a set of useful array words yet;
 2986: the needs are just too diverse, and named, global arrays (the result of
 2987: naive use of defining words) are often not flexible enough (e.g.,
 2988: consider how to pass them as parameters).  Another such project is a set
 2989: of words to help dealing with strings.
 2990: 
 2991: On the other hand, there is a useful set of record words, and it has
 2992: been defined in @file{compat/struct.fs}; these words are predefined in
 2993: Gforth.  They are explained in depth elsewhere in this manual (see
 2994: @pxref{Structures}).  The @code{simple-field} example above is
 2995: simplified variant of fields in this package.
 2996: 
 2997: 
 2998: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 2999: @section @code{POSTPONE}
 3000: @cindex postpone tutorial
 3001: 
 3002: You can compile the compilation semantics (instead of compiling the
 3003: interpretation semantics) of a word with @code{POSTPONE}:
 3004: 
 3005: @example
 3006: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3007:  POSTPONE + ; immediate
 3008: : foo ( n1 n2 -- n )
 3009:  MY-+ ;
 3010: 1 2 foo .
 3011: see foo
 3012: @end example
 3013: 
 3014: During the definition of @code{foo} the text interpreter performs the
 3015: compilation semantics of @code{MY-+}, which performs the compilation
 3016: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3017: 
 3018: This example also displays separate stack comments for the compilation
 3019: semantics and for the stack effect of the compiled code.  For words with
 3020: default compilation semantics these stack effects are usually not
 3021: displayed; the stack effect of the compilation semantics is always
 3022: @code{( -- )} for these words, the stack effect for the compiled code is
 3023: the stack effect of the interpretation semantics.
 3024: 
 3025: Note that the state of the interpreter does not come into play when
 3026: performing the compilation semantics in this way.  You can also perform
 3027: it interpretively, e.g.:
 3028: 
 3029: @example
 3030: : foo2 ( n1 n2 -- n )
 3031:  [ MY-+ ] ;
 3032: 1 2 foo .
 3033: see foo
 3034: @end example
 3035: 
 3036: However, there are some broken Forth systems where this does not always
 3037: work, and therefore this practice was been declared non-standard in
 3038: 1999.
 3039: @c !! repair.fs
 3040: 
 3041: Here is another example for using @code{POSTPONE}:
 3042: 
 3043: @example
 3044: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3045:  POSTPONE negate POSTPONE + ; immediate compile-only
 3046: : bar ( n1 n2 -- n )
 3047:   MY-- ;
 3048: 2 1 bar .
 3049: see bar
 3050: @end example
 3051: 
 3052: You can define @code{ENDIF} in this way:
 3053: 
 3054: @example
 3055: : ENDIF ( Compilation: orig -- )
 3056:   POSTPONE then ; immediate
 3057: @end example
 3058: 
 3059: @assignment
 3060: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3061: @code{2dup}, but compiles @code{over over}.
 3062: @endassignment
 3063: 
 3064: @c !! @xref{Macros} for reference
 3065: 
 3066: 
 3067: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3068: @section @code{Literal}
 3069: @cindex literal tutorial
 3070: 
 3071: You cannot @code{POSTPONE} numbers:
 3072: 
 3073: @example
 3074: : [FOO] POSTPONE 500 ; immediate
 3075: @end example
 3076: 
 3077: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3078: 
 3079: @example
 3080: : [FOO] ( compilation: --; run-time: -- n )
 3081:   500 POSTPONE literal ; immediate
 3082: 
 3083: : flip [FOO] ;
 3084: flip .
 3085: see flip
 3086: @end example
 3087: 
 3088: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3089: semantics are executed) and pushes it at run-time (when the code it
 3090: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3091: number computed at compile time into the current word:
 3092: 
 3093: @example
 3094: : bar ( -- n )
 3095:   [ 2 2 + ] literal ;
 3096: see bar
 3097: @end example
 3098: 
 3099: @assignment
 3100: Write @code{]L} which allows writing the example above as @code{: bar (
 3101: -- n ) [ 2 2 + ]L ;}
 3102: @endassignment
 3103: 
 3104: @c !! @xref{Macros} for reference
 3105: 
 3106: 
 3107: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3108: @section Advanced macros
 3109: @cindex macros, advanced tutorial
 3110: @cindex run-time code generation, tutorial
 3111: 
 3112: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3113: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3114: expensive operation in some Forth implementations.  You can use
 3115: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3116: and produce a word that contains the word to be performed directly:
 3117: 
 3118: @c use ]] ... [[
 3119: @example
 3120: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3121: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3122: \ array beginning at addr and containing u elements
 3123:   @{ xt @}
 3124:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3125:     POSTPONE i POSTPONE @@ xt compile,
 3126:   1 cells POSTPONE literal POSTPONE +loop ;
 3127: 
 3128: : sum-array ( addr u -- n )
 3129:  0 rot rot [ ' + compile-map-array ] ;
 3130: see sum-array
 3131: a 5 sum-array .
 3132: @end example
 3133: 
 3134: You can use the full power of Forth for generating the code; here's an
 3135: example where the code is generated in a loop:
 3136: 
 3137: @example
 3138: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3139: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3140:   POSTPONE tuck POSTPONE @@
 3141:   POSTPONE literal POSTPONE * POSTPONE +
 3142:   POSTPONE swap POSTPONE cell+ ;
 3143: 
 3144: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3145: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3146:   0 postpone literal postpone swap
 3147:   [ ' compile-vmul-step compile-map-array ]
 3148:   postpone drop ;
 3149: see compile-vmul
 3150: 
 3151: : a-vmul ( addr -- n )
 3152: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3153:  [ a 5 compile-vmul ] ;
 3154: see a-vmul
 3155: a a-vmul .
 3156: @end example
 3157: 
 3158: This example uses @code{compile-map-array} to show off, but you could
 3159: also use @code{map-array} instead (try it now!).
 3160: 
 3161: You can use this technique for efficient multiplication of large
 3162: matrices.  In matrix multiplication, you multiply every line of one
 3163: matrix with every column of the other matrix.  You can generate the code
 3164: for one line once, and use it for every column.  The only downside of
 3165: this technique is that it is cumbersome to recover the memory consumed
 3166: by the generated code when you are done (and in more complicated cases
 3167: it is not possible portably).
 3168: 
 3169: @c !! @xref{Macros} for reference
 3170: 
 3171: 
 3172: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3173: @section Compilation Tokens
 3174: @cindex compilation tokens, tutorial
 3175: @cindex CT, tutorial
 3176: 
 3177: This section is Gforth-specific.  You can skip it.
 3178: 
 3179: @code{' word compile,} compiles the interpretation semantics.  For words
 3180: with default compilation semantics this is the same as performing the
 3181: compilation semantics.  To represent the compilation semantics of other
 3182: words (e.g., words like @code{if} that have no interpretation
 3183: semantics), Gforth has the concept of a compilation token (CT,
 3184: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3185: You can perform the compilation semantics represented by a CT with
 3186: @code{execute}:
 3187: 
 3188: @example
 3189: : foo2 ( n1 n2 -- n )
 3190:    [ comp' + execute ] ;
 3191: see foo
 3192: @end example
 3193: 
 3194: You can compile the compilation semantics represented by a CT with
 3195: @code{postpone,}:
 3196: 
 3197: @example
 3198: : foo3 ( -- )
 3199:   [ comp' + postpone, ] ;
 3200: see foo3
 3201: @end example
 3202: 
 3203: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3204: @code{comp'} is particularly useful for words that have no
 3205: interpretation semantics:
 3206: 
 3207: @example
 3208: ' if
 3209: comp' if .s 2drop
 3210: @end example
 3211: 
 3212: Reference: @ref{Tokens for Words}.
 3213: 
 3214: 
 3215: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3216: @section Wordlists and Search Order
 3217: @cindex wordlists tutorial
 3218: @cindex search order, tutorial
 3219: 
 3220: The dictionary is not just a memory area that allows you to allocate
 3221: memory with @code{allot}, it also contains the Forth words, arranged in
 3222: several wordlists.  When searching for a word in a wordlist,
 3223: conceptually you start searching at the youngest and proceed towards
 3224: older words (in reality most systems nowadays use hash-tables); i.e., if
 3225: you define a word with the same name as an older word, the new word
 3226: shadows the older word.
 3227: 
 3228: Which wordlists are searched in which order is determined by the search
 3229: order.  You can display the search order with @code{order}.  It displays
 3230: first the search order, starting with the wordlist searched first, then
 3231: it displays the wordlist that will contain newly defined words.
 3232: 
 3233: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3234: 
 3235: @example
 3236: wordlist constant mywords
 3237: @end example
 3238: 
 3239: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3240: defined words (the @emph{current} wordlist):
 3241: 
 3242: @example
 3243: mywords set-current
 3244: order
 3245: @end example
 3246: 
 3247: Gforth does not display a name for the wordlist in @code{mywords}
 3248: because this wordlist was created anonymously with @code{wordlist}.
 3249: 
 3250: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3251: you want to put something into a specific wordlist without overall
 3252: effect on the current wordlist, this typically looks like this:
 3253: 
 3254: @example
 3255: get-current mywords set-current ( wid )
 3256: create someword
 3257: ( wid ) set-current
 3258: @end example
 3259: 
 3260: You can write the search order with @code{set-order ( wid1 .. widn n --
 3261: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3262: searched wordlist is topmost.
 3263: 
 3264: @example
 3265: get-order mywords swap 1+ set-order
 3266: order
 3267: @end example
 3268: 
 3269: Yes, the order of wordlists in the output of @code{order} is reversed
 3270: from stack comments and the output of @code{.s} and thus unintuitive.
 3271: 
 3272: @assignment
 3273: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3274: wordlist to the search order.  Define @code{previous ( -- )}, which
 3275: removes the first searched wordlist from the search order.  Experiment
 3276: with boundary conditions (you will see some crashes or situations that
 3277: are hard or impossible to leave).
 3278: @endassignment
 3279: 
 3280: The search order is a powerful foundation for providing features similar
 3281: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3282: programs in this way has disadvantages for debugging and reuse/factoring
 3283: that overcome the advantages in my experience (I don't do huge projects,
 3284: though).  These disadvantages are not so clear in other
 3285: languages/programming environments, because these languages are not so
 3286: strong in debugging and reuse.
 3287: 
 3288: @c !! example
 3289: 
 3290: Reference: @ref{Word Lists}.
 3291: 
 3292: @c ******************************************************************
 3293: @node Introduction, Words, Tutorial, Top
 3294: @comment node-name,     next,           previous, up
 3295: @chapter An Introduction to ANS Forth
 3296: @cindex Forth - an introduction
 3297: 
 3298: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3299: that it is slower-paced in its examples, but uses them to dive deep into
 3300: explaining Forth internals (not covered by the Tutorial).  Apart from
 3301: that, this chapter covers far less material.  It is suitable for reading
 3302: without using a computer.
 3303: 
 3304: The primary purpose of this manual is to document Gforth. However, since
 3305: Forth is not a widely-known language and there is a lack of up-to-date
 3306: teaching material, it seems worthwhile to provide some introductory
 3307: material.  For other sources of Forth-related
 3308: information, see @ref{Forth-related information}.
 3309: 
 3310: The examples in this section should work on any ANS Forth; the
 3311: output shown was produced using Gforth. Each example attempts to
 3312: reproduce the exact output that Gforth produces. If you try out the
 3313: examples (and you should), what you should type is shown @kbd{like this}
 3314: and Gforth's response is shown @code{like this}. The single exception is
 3315: that, where the example shows @key{RET} it means that you should
 3316: press the ``carriage return'' key. Unfortunately, some output formats for
 3317: this manual cannot show the difference between @kbd{this} and
 3318: @code{this} which will make trying out the examples harder (but not
 3319: impossible).
 3320: 
 3321: Forth is an unusual language. It provides an interactive development
 3322: environment which includes both an interpreter and compiler. Forth
 3323: programming style encourages you to break a problem down into many
 3324: @cindex factoring
 3325: small fragments (@dfn{factoring}), and then to develop and test each
 3326: fragment interactively. Forth advocates assert that breaking the
 3327: edit-compile-test cycle used by conventional programming languages can
 3328: lead to great productivity improvements.
 3329: 
 3330: @menu
 3331: * Introducing the Text Interpreter::  
 3332: * Stacks and Postfix notation::  
 3333: * Your first definition::       
 3334: * How does that work?::         
 3335: * Forth is written in Forth::   
 3336: * Review - elements of a Forth system::  
 3337: * Where to go next::            
 3338: * Exercises::                   
 3339: @end menu
 3340: 
 3341: @comment ----------------------------------------------
 3342: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3343: @section Introducing the Text Interpreter
 3344: @cindex text interpreter
 3345: @cindex outer interpreter
 3346: 
 3347: @c IMO this is too detailed and the pace is too slow for
 3348: @c an introduction.  If you know German, take a look at
 3349: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3350: @c to see how I do it - anton 
 3351: 
 3352: @c nac-> Where I have accepted your comments 100% and modified the text
 3353: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3354: @c response like this to attempt to rationalise what I have done. Of
 3355: @c course, this is a very clumsy mechanism for something that would be
 3356: @c done far more efficiently over a beer. Please delete any dialogue
 3357: @c you consider closed.
 3358: 
 3359: When you invoke the Forth image, you will see a startup banner printed
 3360: and nothing else (if you have Gforth installed on your system, try
 3361: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3362: its command line interpreter, which is called the @dfn{Text Interpreter}
 3363: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3364: about the text interpreter as you read through this chapter, for more
 3365: detail @pxref{The Text Interpreter}).
 3366: 
 3367: Although it's not obvious, Forth is actually waiting for your
 3368: input. Type a number and press the @key{RET} key:
 3369: 
 3370: @example
 3371: @kbd{45@key{RET}}  ok
 3372: @end example
 3373: 
 3374: Rather than give you a prompt to invite you to input something, the text
 3375: interpreter prints a status message @i{after} it has processed a line
 3376: of input. The status message in this case (``@code{ ok}'' followed by
 3377: carriage-return) indicates that the text interpreter was able to process
 3378: all of your input successfully. Now type something illegal:
 3379: 
 3380: @example
 3381: @kbd{qwer341@key{RET}}
 3382: *the terminal*:2: Undefined word
 3383: >>>qwer341<<<
 3384: Backtrace:
 3385: $2A95B42A20 throw 
 3386: $2A95B57FB8 no.extensions 
 3387: @end example
 3388: 
 3389: The exact text, other than the ``Undefined word'' may differ slightly
 3390: on your system, but the effect is the same; when the text interpreter
 3391: detects an error, it discards any remaining text on a line, resets
 3392: certain internal state and prints an error message. For a detailed
 3393: description of error messages see @ref{Error messages}.
 3394: 
 3395: The text interpreter waits for you to press carriage-return, and then
 3396: processes your input line. Starting at the beginning of the line, it
 3397: breaks the line into groups of characters separated by spaces. For each
 3398: group of characters in turn, it makes two attempts to do something:
 3399: 
 3400: @itemize @bullet
 3401: @item
 3402: @cindex name dictionary
 3403: It tries to treat it as a command. It does this by searching a @dfn{name
 3404: dictionary}. If the group of characters matches an entry in the name
 3405: dictionary, the name dictionary provides the text interpreter with
 3406: information that allows the text interpreter perform some actions. In
 3407: Forth jargon, we say that the group
 3408: @cindex word
 3409: @cindex definition
 3410: @cindex execution token
 3411: @cindex xt
 3412: of characters names a @dfn{word}, that the dictionary search returns an
 3413: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3414: word, and that the text interpreter executes the xt. Often, the terms
 3415: @dfn{word} and @dfn{definition} are used interchangeably.
 3416: @item
 3417: If the text interpreter fails to find a match in the name dictionary, it
 3418: tries to treat the group of characters as a number in the current number
 3419: base (when you start up Forth, the current number base is base 10). If
 3420: the group of characters legitimately represents a number, the text
 3421: interpreter pushes the number onto a stack (we'll learn more about that
 3422: in the next section).
 3423: @end itemize
 3424: 
 3425: If the text interpreter is unable to do either of these things with any
 3426: group of characters, it discards the group of characters and the rest of
 3427: the line, then prints an error message. If the text interpreter reaches
 3428: the end of the line without error, it prints the status message ``@code{ ok}''
 3429: followed by carriage-return.
 3430: 
 3431: This is the simplest command we can give to the text interpreter:
 3432: 
 3433: @example
 3434: @key{RET}  ok
 3435: @end example
 3436: 
 3437: The text interpreter did everything we asked it to do (nothing) without
 3438: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3439: command:
 3440: 
 3441: @example
 3442: @kbd{12 dup fred dup@key{RET}}
 3443: *the terminal*:3: Undefined word
 3444: 12 dup >>>fred<<< dup
 3445: Backtrace:
 3446: $2A95B42A20 throw 
 3447: $2A95B57FB8 no.extensions 
 3448: @end example
 3449: 
 3450: When you press the carriage-return key, the text interpreter starts to
 3451: work its way along the line:
 3452: 
 3453: @itemize @bullet
 3454: @item
 3455: When it gets to the space after the @code{2}, it takes the group of
 3456: characters @code{12} and looks them up in the name
 3457: dictionary@footnote{We can't tell if it found them or not, but assume
 3458: for now that it did not}. There is no match for this group of characters
 3459: in the name dictionary, so it tries to treat them as a number. It is
 3460: able to do this successfully, so it puts the number, 12, ``on the stack''
 3461: (whatever that means).
 3462: @item
 3463: The text interpreter resumes scanning the line and gets the next group
 3464: of characters, @code{dup}. It looks it up in the name dictionary and
 3465: (you'll have to take my word for this) finds it, and executes the word
 3466: @code{dup} (whatever that means).
 3467: @item
 3468: Once again, the text interpreter resumes scanning the line and gets the
 3469: group of characters @code{fred}. It looks them up in the name
 3470: dictionary, but can't find them. It tries to treat them as a number, but
 3471: they don't represent any legal number.
 3472: @end itemize
 3473: 
 3474: At this point, the text interpreter gives up and prints an error
 3475: message. The error message shows exactly how far the text interpreter
 3476: got in processing the line. In particular, it shows that the text
 3477: interpreter made no attempt to do anything with the final character
 3478: group, @code{dup}, even though we have good reason to believe that the
 3479: text interpreter would have no problem looking that word up and
 3480: executing it a second time.
 3481: 
 3482: 
 3483: @comment ----------------------------------------------
 3484: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3485: @section Stacks, postfix notation and parameter passing
 3486: @cindex text interpreter
 3487: @cindex outer interpreter
 3488: 
 3489: In procedural programming languages (like C and Pascal), the
 3490: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3491: functions or procedures are called with @dfn{explicit parameters}. For
 3492: example, in C we might write:
 3493: 
 3494: @example
 3495: total = total + new_volume(length,height,depth);
 3496: @end example
 3497: 
 3498: @noindent
 3499: where new_volume is a function-call to another piece of code, and total,
 3500: length, height and depth are all variables. length, height and depth are
 3501: parameters to the function-call.
 3502: 
 3503: In Forth, the equivalent of the function or procedure is the
 3504: @dfn{definition} and parameters are implicitly passed between
 3505: definitions using a shared stack that is visible to the
 3506: programmer. Although Forth does support variables, the existence of the
 3507: stack means that they are used far less often than in most other
 3508: programming languages. When the text interpreter encounters a number, it
 3509: will place (@dfn{push}) it on the stack. There are several stacks (the
 3510: actual number is implementation-dependent ...) and the particular stack
 3511: used for any operation is implied unambiguously by the operation being
 3512: performed. The stack used for all integer operations is called the @dfn{data
 3513: stack} and, since this is the stack used most commonly, references to
 3514: ``the data stack'' are often abbreviated to ``the stack''.
 3515: 
 3516: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3517: 
 3518: @example
 3519: @kbd{1 2 3@key{RET}}  ok
 3520: @end example
 3521: 
 3522: Then this instructs the text interpreter to placed three numbers on the
 3523: (data) stack. An analogy for the behaviour of the stack is to take a
 3524: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3525: the table. The 3 was the last card onto the pile (``last-in'') and if
 3526: you take a card off the pile then, unless you're prepared to fiddle a
 3527: bit, the card that you take off will be the 3 (``first-out''). The
 3528: number that will be first-out of the stack is called the @dfn{top of
 3529: stack}, which
 3530: @cindex TOS definition
 3531: is often abbreviated to @dfn{TOS}.
 3532: 
 3533: To understand how parameters are passed in Forth, consider the
 3534: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3535: be surprised to learn that this definition performs addition. More
 3536: precisely, it adds two number together and produces a result. Where does
 3537: it get the two numbers from? It takes the top two numbers off the
 3538: stack. Where does it place the result? On the stack. You can act-out the
 3539: behaviour of @code{+} with your playing cards like this:
 3540: 
 3541: @itemize @bullet
 3542: @item
 3543: Pick up two cards from the stack on the table
 3544: @item
 3545: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3546: numbers''
 3547: @item
 3548: Decide that the answer is 5
 3549: @item
 3550: Shuffle the two cards back into the pack and find a 5
 3551: @item
 3552: Put a 5 on the remaining ace that's on the table.
 3553: @end itemize
 3554: 
 3555: If you don't have a pack of cards handy but you do have Forth running,
 3556: you can use the definition @code{.s} to show the current state of the stack,
 3557: without affecting the stack. Type:
 3558: 
 3559: @example
 3560: @kbd{clearstacks 1 2 3@key{RET}} ok
 3561: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3562: @end example
 3563: 
 3564: The text interpreter looks up the word @code{clearstacks} and executes
 3565: it; it tidies up the stacks and removes any entries that may have been
 3566: left on it by earlier examples. The text interpreter pushes each of the
 3567: three numbers in turn onto the stack. Finally, the text interpreter
 3568: looks up the word @code{.s} and executes it. The effect of executing
 3569: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3570: followed by a list of all the items on the stack; the item on the far
 3571: right-hand side is the TOS.
 3572: 
 3573: You can now type:
 3574: 
 3575: @example
 3576: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3577: @end example
 3578: 
 3579: @noindent
 3580: which is correct; there are now 2 items on the stack and the result of
 3581: the addition is 5.
 3582: 
 3583: If you're playing with cards, try doing a second addition: pick up the
 3584: two cards, work out that their sum is 6, shuffle them into the pack,
 3585: look for a 6 and place that on the table. You now have just one item on
 3586: the stack. What happens if you try to do a third addition? Pick up the
 3587: first card, pick up the second card -- ah! There is no second card. This
 3588: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3589: do the same thing with Forth it often reports an error (probably a Stack
 3590: Underflow or an Invalid Memory Address error).
 3591: 
 3592: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3593: which simply accepts that there is a finite amount of storage space
 3594: reserved for the stack. To stretch the playing card analogy, if you had
 3595: enough packs of cards and you piled the cards up on the table, you would
 3596: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3597: allows you to set the maximum size of the stacks. In general, the only
 3598: time that you will get a stack overflow is because a definition has a
 3599: bug in it and is generating data on the stack uncontrollably.
 3600: 
 3601: There's one final use for the playing card analogy. If you model your
 3602: stack using a pack of playing cards, the maximum number of items on
 3603: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3604: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3605: possible numbers are positive integer numbers 1 through 13; you can't
 3606: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3607: think about some of the cards, you can accommodate different
 3608: numbers. For example, you could think of the Jack as representing 0,
 3609: the Queen as representing -1 and the King as representing -2. Your
 3610: @i{range} remains unchanged (you can still only represent a total of 13
 3611: numbers) but the numbers that you can represent are -2 through 10.
 3612: 
 3613: In that analogy, the limit was the amount of information that a single
 3614: stack entry could hold, and Forth has a similar limit. In Forth, the
 3615: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3616: implementation dependent and affects the maximum value that a stack
 3617: entry can hold. A Standard Forth provides a cell size of at least
 3618: 16-bits, and most desktop systems use a cell size of 32-bits.
 3619: 
 3620: Forth does not do any type checking for you, so you are free to
 3621: manipulate and combine stack items in any way you wish. A convenient way
 3622: of treating stack items is as 2's complement signed integers, and that
 3623: is what Standard words like @code{+} do. Therefore you can type:
 3624: 
 3625: @example
 3626: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3627: @end example
 3628: 
 3629: If you use numbers and definitions like @code{+} in order to turn Forth
 3630: into a great big pocket calculator, you will realise that it's rather
 3631: different from a normal calculator. Rather than typing 2 + 3 = you had
 3632: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3633: result). The terminology used to describe this difference is to say that
 3634: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3635: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3636: operators are separate), also called @dfn{Reverse Polish Notation}.
 3637: 
 3638: Whilst postfix notation might look confusing to begin with, it has
 3639: several important advantages:
 3640: 
 3641: @itemize @bullet
 3642: @item
 3643: it is unambiguous
 3644: @item
 3645: it is more concise
 3646: @item
 3647: it fits naturally with a stack-based system
 3648: @end itemize
 3649: 
 3650: To examine these claims in more detail, consider these sums:
 3651: 
 3652: @example
 3653: 6 + 5 * 4 =
 3654: 4 * 5 + 6 =
 3655: @end example
 3656: 
 3657: If you're just learning maths or your maths is very rusty, you will
 3658: probably come up with the answer 44 for the first and 26 for the
 3659: second. If you are a bit of a whizz at maths you will remember the
 3660: @i{convention} that multiplication takes precendence over addition, and
 3661: you'd come up with the answer 26 both times. To explain the answer 26
 3662: to someone who got the answer 44, you'd probably rewrite the first sum
 3663: like this:
 3664: 
 3665: @example
 3666: 6 + (5 * 4) =
 3667: @end example
 3668: 
 3669: If what you really wanted was to perform the addition before the
 3670: multiplication, you would have to use parentheses to force it.
 3671: 
 3672: If you did the first two sums on a pocket calculator you would probably
 3673: get the right answers, unless you were very cautious and entered them using
 3674: these keystroke sequences:
 3675: 
 3676: 6 + 5 = * 4 =
 3677: 4 * 5 = + 6 =
 3678: 
 3679: Postfix notation is unambiguous because the order that the operators
 3680: are applied is always explicit; that also means that parentheses are
 3681: never required. The operators are @i{active} (the act of quoting the
 3682: operator makes the operation occur) which removes the need for ``=''.
 3683: 
 3684: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3685: equivalent ways:
 3686: 
 3687: @example
 3688: 6 5 4 * +      or:
 3689: 5 4 * 6 +
 3690: @end example
 3691: 
 3692: An important thing that you should notice about this notation is that
 3693: the @i{order} of the numbers does not change; if you want to subtract
 3694: 2 from 10 you type @code{10 2 -}.
 3695: 
 3696: The reason that Forth uses postfix notation is very simple to explain: it
 3697: makes the implementation extremely simple, and it follows naturally from
 3698: using the stack as a mechanism for passing parameters. Another way of
 3699: thinking about this is to realise that all Forth definitions are
 3700: @i{active}; they execute as they are encountered by the text
 3701: interpreter. The result of this is that the syntax of Forth is trivially
 3702: simple.
 3703: 
 3704: 
 3705: 
 3706: @comment ----------------------------------------------
 3707: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3708: @section Your first Forth definition
 3709: @cindex first definition
 3710: 
 3711: Until now, the examples we've seen have been trivial; we've just been
 3712: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3713: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3714: again@footnote{That's not quite true. If you press the up-arrow key on
 3715: your keyboard you should be able to scroll back to any earlier command,
 3716: edit it and re-enter it.} In this section we'll see how to add new
 3717: words to Forth's vocabulary.
 3718: 
 3719: The easiest way to create a new word is to use a @dfn{colon
 3720: definition}. We'll define a few and try them out before worrying too
 3721: much about how they work. Try typing in these examples; be careful to
 3722: copy the spaces accurately:
 3723: 
 3724: @example
 3725: : add-two 2 + . ;
 3726: : greet ." Hello and welcome" ;
 3727: : demo 5 add-two ;
 3728: @end example
 3729: 
 3730: @noindent
 3731: Now try them out:
 3732: 
 3733: @example
 3734: @kbd{greet@key{RET}} Hello and welcome  ok
 3735: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3736: @kbd{4 add-two@key{RET}} 6  ok
 3737: @kbd{demo@key{RET}} 7  ok
 3738: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3739: @end example
 3740: 
 3741: The first new thing that we've introduced here is the pair of words
 3742: @code{:} and @code{;}. These are used to start and terminate a new
 3743: definition, respectively. The first word after the @code{:} is the name
 3744: for the new definition.
 3745: 
 3746: As you can see from the examples, a definition is built up of words that
 3747: have already been defined; Forth makes no distinction between
 3748: definitions that existed when you started the system up, and those that
 3749: you define yourself.
 3750: 
 3751: The examples also introduce the words @code{.} (dot), @code{."}
 3752: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3753: the stack and displays it. It's like @code{.s} except that it only
 3754: displays the top item of the stack and it is destructive; after it has
 3755: executed, the number is no longer on the stack. There is always one
 3756: space printed after the number, and no spaces before it. Dot-quote
 3757: defines a string (a sequence of characters) that will be printed when
 3758: the word is executed. The string can contain any printable characters
 3759: except @code{"}. A @code{"} has a special function; it is not a Forth
 3760: word but it acts as a delimiter (the way that delimiters work is
 3761: described in the next section). Finally, @code{dup} duplicates the value
 3762: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3763: 
 3764: We already know that the text interpreter searches through the
 3765: dictionary to locate names. If you've followed the examples earlier, you
 3766: will already have a definition called @code{add-two}. Lets try modifying
 3767: it by typing in a new definition:
 3768: 
 3769: @example
 3770: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3771: @end example
 3772: 
 3773: Forth recognised that we were defining a word that already exists, and
 3774: printed a message to warn us of that fact. Let's try out the new
 3775: definition:
 3776: 
 3777: @example
 3778: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3779: @end example
 3780: 
 3781: @noindent
 3782: All that we've actually done here, though, is to create a new
 3783: definition, with a particular name. The fact that there was already a
 3784: definition with the same name did not make any difference to the way
 3785: that the new definition was created (except that Forth printed a warning
 3786: message). The old definition of add-two still exists (try @code{demo}
 3787: again to see that this is true). Any new definition will use the new
 3788: definition of @code{add-two}, but old definitions continue to use the
 3789: version that already existed at the time that they were @code{compiled}.
 3790: 
 3791: Before you go on to the next section, try defining and redefining some
 3792: words of your own.
 3793: 
 3794: @comment ----------------------------------------------
 3795: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3796: @section How does that work?
 3797: @cindex parsing words
 3798: 
 3799: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3800: 
 3801: @c Is it a good idea to talk about the interpretation semantics of a
 3802: @c number? We don't have an xt to go along with it. - anton
 3803: 
 3804: @c Now that I have eliminated execution semantics, I wonder if it would not
 3805: @c be better to keep them (or add run-time semantics), to make it easier to
 3806: @c explain what compilation semantics usually does. - anton
 3807: 
 3808: @c nac-> I removed the term ``default compilation sematics'' from the
 3809: @c introductory chapter. Removing ``execution semantics'' was making
 3810: @c everything simpler to explain, then I think the use of this term made
 3811: @c everything more complex again. I replaced it with ``default
 3812: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3813: @c ``a definition that has neither the immediate nor the compile-only
 3814: @c flag set''.
 3815: 
 3816: @c anton: I have eliminated default semantics (except in one place where it
 3817: @c means "default interpretation and compilation semantics"), because it
 3818: @c makes no sense in the presence of combined words.  I reverted to
 3819: @c "execution semantics" where necessary.
 3820: 
 3821: @c nac-> I reworded big chunks of the ``how does that work''
 3822: @c section (and, unusually for me, I think I even made it shorter!).  See
 3823: @c what you think -- I know I have not addressed your primary concern
 3824: @c that it is too heavy-going for an introduction. From what I understood
 3825: @c of your course notes it looks as though they might be a good framework. 
 3826: @c Things that I've tried to capture here are some things that came as a
 3827: @c great revelation here when I first understood them. Also, I like the
 3828: @c fact that a very simple code example shows up almost all of the issues
 3829: @c that you need to understand to see how Forth works. That's unique and
 3830: @c worthwhile to emphasise.
 3831: 
 3832: @c anton: I think it's a good idea to present the details, especially those
 3833: @c that you found to be a revelation, and probably the tutorial tries to be
 3834: @c too superficial and does not get some of the things across that make
 3835: @c Forth special.  I do believe that most of the time these things should
 3836: @c be discussed at the end of a section or in separate sections instead of
 3837: @c in the middle of a section (e.g., the stuff you added in "User-defined
 3838: @c defining words" leads in a completely different direction from the rest
 3839: @c of the section).
 3840: 
 3841: Now we're going to take another look at the definition of @code{add-two}
 3842: from the previous section. From our knowledge of the way that the text
 3843: interpreter works, we would have expected this result when we tried to
 3844: define @code{add-two}:
 3845: 
 3846: @example
 3847: @kbd{: add-two 2 + . ;@key{RET}}
 3848: *the terminal*:4: Undefined word
 3849: : >>>add-two<<< 2 + . ;
 3850: @end example
 3851: 
 3852: The reason that this didn't happen is bound up in the way that @code{:}
 3853: works. The word @code{:} does two special things. The first special
 3854: thing that it does prevents the text interpreter from ever seeing the
 3855: characters @code{add-two}. The text interpreter uses a variable called
 3856: @cindex modifying >IN
 3857: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3858: input line. When it encounters the word @code{:} it behaves in exactly
 3859: the same way as it does for any other word; it looks it up in the name
 3860: dictionary, finds its xt and executes it. When @code{:} executes, it
 3861: looks at the input buffer, finds the word @code{add-two} and advances the
 3862: value of @code{>IN} to point past it. It then does some other stuff
 3863: associated with creating the new definition (including creating an entry
 3864: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3865: completes, control returns to the text interpreter, which is oblivious
 3866: to the fact that it has been tricked into ignoring part of the input
 3867: line.
 3868: 
 3869: @cindex parsing words
 3870: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3871: prevent the text interpreter from acting on the whole of the input line
 3872: -- are called @dfn{parsing words}.
 3873: 
 3874: @cindex @code{state} - effect on the text interpreter
 3875: @cindex text interpreter - effect of state
 3876: The second special thing that @code{:} does is change the value of a
 3877: variable called @code{state}, which affects the way that the text
 3878: interpreter behaves. When Gforth starts up, @code{state} has the value
 3879: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 3880: colon definition (started with @code{:}), @code{state} is set to -1 and
 3881: the text interpreter is said to be @dfn{compiling}.
 3882: 
 3883: In this example, the text interpreter is compiling when it processes the
 3884: string ``@code{2 + . ;}''. It still breaks the string down into
 3885: character sequences in the same way. However, instead of pushing the
 3886: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 3887: into the definition of @code{add-two} that will make the number @code{2} get
 3888: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 3889: the behaviours of @code{+} and @code{.} are also compiled into the
 3890: definition.
 3891: 
 3892: One category of words don't get compiled. These so-called @dfn{immediate
 3893: words} get executed (performed @i{now}) regardless of whether the text
 3894: interpreter is interpreting or compiling. The word @code{;} is an
 3895: immediate word. Rather than being compiled into the definition, it
 3896: executes. Its effect is to terminate the current definition, which
 3897: includes changing the value of @code{state} back to 0.
 3898: 
 3899: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 3900: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 3901: definition.
 3902: 
 3903: In Forth, every word or number can be described in terms of two
 3904: properties:
 3905: 
 3906: @itemize @bullet
 3907: @item
 3908: @cindex interpretation semantics
 3909: Its @dfn{interpretation semantics} describe how it will behave when the
 3910: text interpreter encounters it in @dfn{interpret} state. The
 3911: interpretation semantics of a word are represented by an @dfn{execution
 3912: token}.
 3913: @item
 3914: @cindex compilation semantics
 3915: Its @dfn{compilation semantics} describe how it will behave when the
 3916: text interpreter encounters it in @dfn{compile} state. The compilation
 3917: semantics of a word are represented in an implementation-dependent way;
 3918: Gforth uses a @dfn{compilation token}.
 3919: @end itemize
 3920: 
 3921: @noindent
 3922: Numbers are always treated in a fixed way:
 3923: 
 3924: @itemize @bullet
 3925: @item
 3926: When the number is @dfn{interpreted}, its behaviour is to push the
 3927: number onto the stack.
 3928: @item
 3929: When the number is @dfn{compiled}, a piece of code is appended to the
 3930: current definition that pushes the number when it runs. (In other words,
 3931: the compilation semantics of a number are to postpone its interpretation
 3932: semantics until the run-time of the definition that it is being compiled
 3933: into.)
 3934: @end itemize
 3935: 
 3936: Words don't behave in such a regular way, but most have @i{default
 3937: semantics} which means that they behave like this:
 3938: 
 3939: @itemize @bullet
 3940: @item
 3941: The @dfn{interpretation semantics} of the word are to do something useful.
 3942: @item
 3943: The @dfn{compilation semantics} of the word are to append its
 3944: @dfn{interpretation semantics} to the current definition (so that its
 3945: run-time behaviour is to do something useful).
 3946: @end itemize
 3947: 
 3948: @cindex immediate words
 3949: The actual behaviour of any particular word can be controlled by using
 3950: the words @code{immediate} and @code{compile-only} when the word is
 3951: defined. These words set flags in the name dictionary entry of the most
 3952: recently defined word, and these flags are retrieved by the text
 3953: interpreter when it finds the word in the name dictionary.
 3954: 
 3955: A word that is marked as @dfn{immediate} has compilation semantics that
 3956: are identical to its interpretation semantics. In other words, it
 3957: behaves like this:
 3958: 
 3959: @itemize @bullet
 3960: @item
 3961: The @dfn{interpretation semantics} of the word are to do something useful.
 3962: @item
 3963: The @dfn{compilation semantics} of the word are to do something useful
 3964: (and actually the same thing); i.e., it is executed during compilation.
 3965: @end itemize
 3966: 
 3967: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 3968: performing the interpretation semantics of the word directly; an attempt
 3969: to do so will generate an error. It is never necessary to use
 3970: @code{compile-only} (and it is not even part of ANS Forth, though it is
 3971: provided by many implementations) but it is good etiquette to apply it
 3972: to a word that will not behave correctly (and might have unexpected
 3973: side-effects) in interpret state. For example, it is only legal to use
 3974: the conditional word @code{IF} within a definition. If you forget this
 3975: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 3976: @code{compile-only} allows the text interpreter to generate a helpful
 3977: error message rather than subjecting you to the consequences of your
 3978: folly.
 3979: 
 3980: This example shows the difference between an immediate and a
 3981: non-immediate word:
 3982: 
 3983: @example
 3984: : show-state state @@ . ;
 3985: : show-state-now show-state ; immediate
 3986: : word1 show-state ;
 3987: : word2 show-state-now ;
 3988: @end example
 3989: 
 3990: The word @code{immediate} after the definition of @code{show-state-now}
 3991: makes that word an immediate word. These definitions introduce a new
 3992: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 3993: variable, and leaves it on the stack. Therefore, the behaviour of
 3994: @code{show-state} is to print a number that represents the current value
 3995: of @code{state}.
 3996: 
 3997: When you execute @code{word1}, it prints the number 0, indicating that
 3998: the system is interpreting. When the text interpreter compiled the
 3999: definition of @code{word1}, it encountered @code{show-state} whose
 4000: compilation semantics are to append its interpretation semantics to the
 4001: current definition. When you execute @code{word1}, it performs the
 4002: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4003: (and therefore @code{show-state}) are executed, the system is
 4004: interpreting.
 4005: 
 4006: When you pressed @key{RET} after entering the definition of @code{word2},
 4007: you should have seen the number -1 printed, followed by ``@code{
 4008: ok}''. When the text interpreter compiled the definition of
 4009: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4010: whose compilation semantics are therefore to perform its interpretation
 4011: semantics. It is executed straight away (even before the text
 4012: interpreter has moved on to process another group of characters; the
 4013: @code{;} in this example). The effect of executing it are to display the
 4014: value of @code{state} @i{at the time that the definition of}
 4015: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4016: system is compiling at this time. If you execute @code{word2} it does
 4017: nothing at all.
 4018: 
 4019: @cindex @code{."}, how it works
 4020: Before leaving the subject of immediate words, consider the behaviour of
 4021: @code{."} in the definition of @code{greet}, in the previous
 4022: section. This word is both a parsing word and an immediate word. Notice
 4023: that there is a space between @code{."} and the start of the text
 4024: @code{Hello and welcome}, but that there is no space between the last
 4025: letter of @code{welcome} and the @code{"} character. The reason for this
 4026: is that @code{."} is a Forth word; it must have a space after it so that
 4027: the text interpreter can identify it. The @code{"} is not a Forth word;
 4028: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4029: is displayed, there is neither a space before the @code{H} nor after the
 4030: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4031: that @code{greet} is defined. When it executes, its behaviour is to
 4032: search forward in the input line looking for the delimiter. When it
 4033: finds the delimiter, it updates @code{>IN} to point past the
 4034: delimiter. It also compiles some magic code into the definition of
 4035: @code{greet}; the xt of a run-time routine that prints a text string. It
 4036: compiles the string @code{Hello and welcome} into memory so that it is
 4037: available to be printed later. When the text interpreter gains control,
 4038: the next word it finds in the input stream is @code{;} and so it
 4039: terminates the definition of @code{greet}.
 4040: 
 4041: 
 4042: @comment ----------------------------------------------
 4043: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4044: @section Forth is written in Forth
 4045: @cindex structure of Forth programs
 4046: 
 4047: When you start up a Forth compiler, a large number of definitions
 4048: already exist. In Forth, you develop a new application using bottom-up
 4049: programming techniques to create new definitions that are defined in
 4050: terms of existing definitions. As you create each definition you can
 4051: test and debug it interactively.
 4052: 
 4053: If you have tried out the examples in this section, you will probably
 4054: have typed them in by hand; when you leave Gforth, your definitions will
 4055: be lost. You can avoid this by using a text editor to enter Forth source
 4056: code into a file, and then loading code from the file using
 4057: @code{include} (@pxref{Forth source files}). A Forth source file is
 4058: processed by the text interpreter, just as though you had typed it in by
 4059: hand@footnote{Actually, there are some subtle differences -- see
 4060: @ref{The Text Interpreter}.}.
 4061: 
 4062: Gforth also supports the traditional Forth alternative to using text
 4063: files for program entry (@pxref{Blocks}).
 4064: 
 4065: In common with many, if not most, Forth compilers, most of Gforth is
 4066: actually written in Forth. All of the @file{.fs} files in the
 4067: installation directory@footnote{For example,
 4068: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4069: study to see examples of Forth programming.
 4070: 
 4071: Gforth maintains a history file that records every line that you type to
 4072: the text interpreter. This file is preserved between sessions, and is
 4073: used to provide a command-line recall facility. If you enter long
 4074: definitions by hand, you can use a text editor to paste them out of the
 4075: history file into a Forth source file for reuse at a later time
 4076: (for more information @pxref{Command-line editing}).
 4077: 
 4078: 
 4079: @comment ----------------------------------------------
 4080: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4081: @section Review - elements of a Forth system
 4082: @cindex elements of a Forth system
 4083: 
 4084: To summarise this chapter:
 4085: 
 4086: @itemize @bullet
 4087: @item
 4088: Forth programs use @dfn{factoring} to break a problem down into small
 4089: fragments called @dfn{words} or @dfn{definitions}.
 4090: @item
 4091: Forth program development is an interactive process.
 4092: @item
 4093: The main command loop that accepts input, and controls both
 4094: interpretation and compilation, is called the @dfn{text interpreter}
 4095: (also known as the @dfn{outer interpreter}).
 4096: @item
 4097: Forth has a very simple syntax, consisting of words and numbers
 4098: separated by spaces or carriage-return characters. Any additional syntax
 4099: is imposed by @dfn{parsing words}.
 4100: @item
 4101: Forth uses a stack to pass parameters between words. As a result, it
 4102: uses postfix notation.
 4103: @item
 4104: To use a word that has previously been defined, the text interpreter
 4105: searches for the word in the @dfn{name dictionary}.
 4106: @item
 4107: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4108: @item
 4109: The text interpreter uses the value of @code{state} to select between
 4110: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4111: semantics} of a word that it encounters.
 4112: @item
 4113: The relationship between the @dfn{interpretation semantics} and
 4114: @dfn{compilation semantics} for a word
 4115: depend upon the way in which the word was defined (for example, whether
 4116: it is an @dfn{immediate} word).
 4117: @item
 4118: Forth definitions can be implemented in Forth (called @dfn{high-level
 4119: definitions}) or in some other way (usually a lower-level language and
 4120: as a result often called @dfn{low-level definitions}, @dfn{code
 4121: definitions} or @dfn{primitives}).
 4122: @item
 4123: Many Forth systems are implemented mainly in Forth.
 4124: @end itemize
 4125: 
 4126: 
 4127: @comment ----------------------------------------------
 4128: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4129: @section Where To Go Next
 4130: @cindex where to go next
 4131: 
 4132: Amazing as it may seem, if you have read (and understood) this far, you
 4133: know almost all the fundamentals about the inner workings of a Forth
 4134: system. You certainly know enough to be able to read and understand the
 4135: rest of this manual and the ANS Forth document, to learn more about the
 4136: facilities that Forth in general and Gforth in particular provide. Even
 4137: scarier, you know almost enough to implement your own Forth system.
 4138: However, that's not a good idea just yet... better to try writing some
 4139: programs in Gforth.
 4140: 
 4141: Forth has such a rich vocabulary that it can be hard to know where to
 4142: start in learning it. This section suggests a few sets of words that are
 4143: enough to write small but useful programs. Use the word index in this
 4144: document to learn more about each word, then try it out and try to write
 4145: small definitions using it. Start by experimenting with these words:
 4146: 
 4147: @itemize @bullet
 4148: @item
 4149: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4150: @item
 4151: Comparison: @code{MIN MAX =}
 4152: @item
 4153: Logic: @code{AND OR XOR NOT}
 4154: @item
 4155: Stack manipulation: @code{DUP DROP SWAP OVER}
 4156: @item
 4157: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4158: @item
 4159: Input/Output: @code{. ." EMIT CR KEY}
 4160: @item
 4161: Defining words: @code{: ; CREATE}
 4162: @item
 4163: Memory allocation words: @code{ALLOT ,}
 4164: @item
 4165: Tools: @code{SEE WORDS .S MARKER}
 4166: @end itemize
 4167: 
 4168: When you have mastered those, go on to:
 4169: 
 4170: @itemize @bullet
 4171: @item
 4172: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4173: @item
 4174: Memory access: @code{@@ !}
 4175: @end itemize
 4176: 
 4177: When you have mastered these, there's nothing for it but to read through
 4178: the whole of this manual and find out what you've missed.
 4179: 
 4180: @comment ----------------------------------------------
 4181: @node Exercises,  , Where to go next, Introduction
 4182: @section Exercises
 4183: @cindex exercises
 4184: 
 4185: TODO: provide a set of programming excercises linked into the stuff done
 4186: already and into other sections of the manual. Provide solutions to all
 4187: the exercises in a .fs file in the distribution.
 4188: 
 4189: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4190: 
 4191: @c excercises:
 4192: @c 1. take inches and convert to feet and inches.
 4193: @c 2. take temperature and convert from fahrenheight to celcius;
 4194: @c    may need to care about symmetric vs floored??
 4195: @c 3. take input line and do character substitution
 4196: @c    to encipher or decipher
 4197: @c 4. as above but work on a file for in and out
 4198: @c 5. take input line and convert to pig-latin 
 4199: @c
 4200: @c thing of sets of things to exercise then come up with
 4201: @c problems that need those things.
 4202: 
 4203: 
 4204: @c ******************************************************************
 4205: @node Words, Error messages, Introduction, Top
 4206: @chapter Forth Words
 4207: @cindex words
 4208: 
 4209: @menu
 4210: * Notation::                    
 4211: * Case insensitivity::          
 4212: * Comments::                    
 4213: * Boolean Flags::               
 4214: * Arithmetic::                  
 4215: * Stack Manipulation::          
 4216: * Memory::                      
 4217: * Control Structures::          
 4218: * Defining Words::              
 4219: * Interpretation and Compilation Semantics::  
 4220: * Tokens for Words::            
 4221: * Compiling words::             
 4222: * The Text Interpreter::        
 4223: * The Input Stream::            
 4224: * Word Lists::                  
 4225: * Environmental Queries::       
 4226: * Files::                       
 4227: * Blocks::                      
 4228: * Other I/O::                   
 4229: * OS command line arguments::   
 4230: * Locals::                      
 4231: * Structures::                  
 4232: * Object-oriented Forth::       
 4233: * Programming Tools::           
 4234: * Assembler and Code Words::    
 4235: * Threading Words::             
 4236: * Passing Commands to the OS::  
 4237: * Keeping track of Time::       
 4238: * Miscellaneous Words::         
 4239: @end menu
 4240: 
 4241: @node Notation, Case insensitivity, Words, Words
 4242: @section Notation
 4243: @cindex notation of glossary entries
 4244: @cindex format of glossary entries
 4245: @cindex glossary notation format
 4246: @cindex word glossary entry format
 4247: 
 4248: The Forth words are described in this section in the glossary notation
 4249: that has become a de-facto standard for Forth texts:
 4250: 
 4251: @format
 4252: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4253: @end format
 4254: @i{Description}
 4255: 
 4256: @table @var
 4257: @item word
 4258: The name of the word.
 4259: 
 4260: @item Stack effect
 4261: @cindex stack effect
 4262: The stack effect is written in the notation @code{@i{before} --
 4263: @i{after}}, where @i{before} and @i{after} describe the top of
 4264: stack entries before and after the execution of the word. The rest of
 4265: the stack is not touched by the word. The top of stack is rightmost,
 4266: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4267: uses a separate floating point stack, but a unified stack
 4268: notation. Also, return stack effects are not shown in @i{stack
 4269: effect}, but in @i{Description}. The name of a stack item describes
 4270: the type and/or the function of the item. See below for a discussion of
 4271: the types.
 4272: 
 4273: All words have two stack effects: A compile-time stack effect and a
 4274: run-time stack effect. The compile-time stack-effect of most words is
 4275: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4276: this standard behaviour, or the word does other unusual things at
 4277: compile time, both stack effects are shown; otherwise only the run-time
 4278: stack effect is shown.
 4279: 
 4280: @cindex pronounciation of words
 4281: @item pronunciation
 4282: How the word is pronounced.
 4283: 
 4284: @cindex wordset
 4285: @cindex environment wordset
 4286: @item wordset
 4287: The ANS Forth standard is divided into several word sets. A standard
 4288: system need not support all of them. Therefore, in theory, the fewer
 4289: word sets your program uses the more portable it will be. However, we
 4290: suspect that most ANS Forth systems on personal machines will feature
 4291: all word sets. Words that are not defined in ANS Forth have
 4292: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4293: describes words that will work in future releases of Gforth;
 4294: @code{gforth-internal} words are more volatile. Environmental query
 4295: strings are also displayed like words; you can recognize them by the
 4296: @code{environment} in the word set field.
 4297: 
 4298: @item Description
 4299: A description of the behaviour of the word.
 4300: @end table
 4301: 
 4302: @cindex types of stack items
 4303: @cindex stack item types
 4304: The type of a stack item is specified by the character(s) the name
 4305: starts with:
 4306: 
 4307: @table @code
 4308: @item f
 4309: @cindex @code{f}, stack item type
 4310: Boolean flags, i.e. @code{false} or @code{true}.
 4311: @item c
 4312: @cindex @code{c}, stack item type
 4313: Char
 4314: @item w
 4315: @cindex @code{w}, stack item type
 4316: Cell, can contain an integer or an address
 4317: @item n
 4318: @cindex @code{n}, stack item type
 4319: signed integer
 4320: @item u
 4321: @cindex @code{u}, stack item type
 4322: unsigned integer
 4323: @item d
 4324: @cindex @code{d}, stack item type
 4325: double sized signed integer
 4326: @item ud
 4327: @cindex @code{ud}, stack item type
 4328: double sized unsigned integer
 4329: @item r
 4330: @cindex @code{r}, stack item type
 4331: Float (on the FP stack)
 4332: @item a-
 4333: @cindex @code{a_}, stack item type
 4334: Cell-aligned address
 4335: @item c-
 4336: @cindex @code{c_}, stack item type
 4337: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4338: @item f-
 4339: @cindex @code{f_}, stack item type
 4340: Float-aligned address
 4341: @item df-
 4342: @cindex @code{df_}, stack item type
 4343: Address aligned for IEEE double precision float
 4344: @item sf-
 4345: @cindex @code{sf_}, stack item type
 4346: Address aligned for IEEE single precision float
 4347: @item xt
 4348: @cindex @code{xt}, stack item type
 4349: Execution token, same size as Cell
 4350: @item wid
 4351: @cindex @code{wid}, stack item type
 4352: Word list ID, same size as Cell
 4353: @item ior, wior
 4354: @cindex ior type description
 4355: @cindex wior type description
 4356: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4357: @item f83name
 4358: @cindex @code{f83name}, stack item type
 4359: Pointer to a name structure
 4360: @item "
 4361: @cindex @code{"}, stack item type
 4362: string in the input stream (not on the stack). The terminating character
 4363: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4364: quotes.
 4365: @end table
 4366: 
 4367: @comment ----------------------------------------------
 4368: @node Case insensitivity, Comments, Notation, Words
 4369: @section Case insensitivity
 4370: @cindex case sensitivity
 4371: @cindex upper and lower case
 4372: 
 4373: Gforth is case-insensitive; you can enter definitions and invoke
 4374: Standard words using upper, lower or mixed case (however,
 4375: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4376: options}).
 4377: 
 4378: ANS Forth only @i{requires} implementations to recognise Standard words
 4379: when they are typed entirely in upper case. Therefore, a Standard
 4380: program must use upper case for all Standard words. You can use whatever
 4381: case you like for words that you define, but in a Standard program you
 4382: have to use the words in the same case that you defined them.
 4383: 
 4384: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4385: wordlists, @pxref{Word Lists}).
 4386: 
 4387: Two people have asked how to convert Gforth to be case-sensitive; while
 4388: we think this is a bad idea, you can change all wordlists into tables
 4389: like this:
 4390: 
 4391: @example
 4392: ' table-find forth-wordlist wordlist-map @ !
 4393: @end example
 4394: 
 4395: Note that you now have to type the predefined words in the same case
 4396: that we defined them, which are varying.  You may want to convert them
 4397: to your favourite case before doing this operation (I won't explain how,
 4398: because if you are even contemplating doing this, you'd better have
 4399: enough knowledge of Forth systems to know this already).
 4400: 
 4401: @node Comments, Boolean Flags, Case insensitivity, Words
 4402: @section Comments
 4403: @cindex comments
 4404: 
 4405: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4406: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4407: 
 4408: 
 4409: doc-(
 4410: doc-\
 4411: doc-\G
 4412: 
 4413: 
 4414: @node Boolean Flags, Arithmetic, Comments, Words
 4415: @section Boolean Flags
 4416: @cindex Boolean flags
 4417: 
 4418: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4419: flag @code{false} and a flag with all bits set represents the flag
 4420: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4421: a cell that has @i{any} bit set as @code{true}.
 4422: @c on and off to Memory? 
 4423: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4424: 
 4425: doc-true
 4426: doc-false
 4427: doc-on
 4428: doc-off
 4429: 
 4430: 
 4431: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4432: @section Arithmetic
 4433: @cindex arithmetic words
 4434: 
 4435: @cindex division with potentially negative operands
 4436: Forth arithmetic is not checked, i.e., you will not hear about integer
 4437: overflow on addition or multiplication, you may hear about division by
 4438: zero if you are lucky. The operator is written after the operands, but
 4439: the operands are still in the original order. I.e., the infix @code{2-1}
 4440: corresponds to @code{2 1 -}. Forth offers a variety of division
 4441: operators. If you perform division with potentially negative operands,
 4442: you do not want to use @code{/} or @code{/mod} with its undefined
 4443: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4444: former, @pxref{Mixed precision}).
 4445: @comment TODO discuss the different division forms and the std approach
 4446: 
 4447: @menu
 4448: * Single precision::            
 4449: * Double precision::            Double-cell integer arithmetic
 4450: * Bitwise operations::          
 4451: * Numeric comparison::          
 4452: * Mixed precision::             Operations with single and double-cell integers
 4453: * Floating Point::              
 4454: @end menu
 4455: 
 4456: @node Single precision, Double precision, Arithmetic, Arithmetic
 4457: @subsection Single precision
 4458: @cindex single precision arithmetic words
 4459: 
 4460: @c !! cell undefined
 4461: 
 4462: By default, numbers in Forth are single-precision integers that are one
 4463: cell in size. They can be signed or unsigned, depending upon how you
 4464: treat them. For the rules used by the text interpreter for recognising
 4465: single-precision integers see @ref{Number Conversion}.
 4466: 
 4467: These words are all defined for signed operands, but some of them also
 4468: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4469: @code{*}.
 4470: 
 4471: doc-+
 4472: doc-1+
 4473: doc-under+
 4474: doc--
 4475: doc-1-
 4476: doc-*
 4477: doc-/
 4478: doc-mod
 4479: doc-/mod
 4480: doc-negate
 4481: doc-abs
 4482: doc-min
 4483: doc-max
 4484: doc-floored
 4485: 
 4486: 
 4487: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4488: @subsection Double precision
 4489: @cindex double precision arithmetic words
 4490: 
 4491: For the rules used by the text interpreter for
 4492: recognising double-precision integers, see @ref{Number Conversion}.
 4493: 
 4494: A double precision number is represented by a cell pair, with the most
 4495: significant cell at the TOS. It is trivial to convert an unsigned single
 4496: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4497: represented by Gforth using 2's complement arithmetic, converting a
 4498: signed single to a (signed) double requires sign-extension across the
 4499: most significant cell. This can be achieved using @code{s>d}. The moral
 4500: of the story is that you cannot convert a number without knowing whether
 4501: it represents an unsigned or a signed number.
 4502: 
 4503: These words are all defined for signed operands, but some of them also
 4504: work for unsigned numbers: @code{d+}, @code{d-}.
 4505: 
 4506: doc-s>d
 4507: doc-d>s
 4508: doc-d+
 4509: doc-d-
 4510: doc-dnegate
 4511: doc-dabs
 4512: doc-dmin
 4513: doc-dmax
 4514: 
 4515: 
 4516: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4517: @subsection Bitwise operations
 4518: @cindex bitwise operation words
 4519: 
 4520: 
 4521: doc-and
 4522: doc-or
 4523: doc-xor
 4524: doc-invert
 4525: doc-lshift
 4526: doc-rshift
 4527: doc-2*
 4528: doc-d2*
 4529: doc-2/
 4530: doc-d2/
 4531: 
 4532: 
 4533: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4534: @subsection Numeric comparison
 4535: @cindex numeric comparison words
 4536: 
 4537: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4538: d0= d0<>}) work for for both signed and unsigned numbers.
 4539: 
 4540: doc-<
 4541: doc-<=
 4542: doc-<>
 4543: doc-=
 4544: doc->
 4545: doc->=
 4546: 
 4547: doc-0<
 4548: doc-0<=
 4549: doc-0<>
 4550: doc-0=
 4551: doc-0>
 4552: doc-0>=
 4553: 
 4554: doc-u<
 4555: doc-u<=
 4556: @c u<> and u= exist but are the same as <> and =
 4557: @c doc-u<>
 4558: @c doc-u=
 4559: doc-u>
 4560: doc-u>=
 4561: 
 4562: doc-within
 4563: 
 4564: doc-d<
 4565: doc-d<=
 4566: doc-d<>
 4567: doc-d=
 4568: doc-d>
 4569: doc-d>=
 4570: 
 4571: doc-d0<
 4572: doc-d0<=
 4573: doc-d0<>
 4574: doc-d0=
 4575: doc-d0>
 4576: doc-d0>=
 4577: 
 4578: doc-du<
 4579: doc-du<=
 4580: @c du<> and du= exist but are the same as d<> and d=
 4581: @c doc-du<>
 4582: @c doc-du=
 4583: doc-du>
 4584: doc-du>=
 4585: 
 4586: 
 4587: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4588: @subsection Mixed precision
 4589: @cindex mixed precision arithmetic words
 4590: 
 4591: 
 4592: doc-m+
 4593: doc-*/
 4594: doc-*/mod
 4595: doc-m*
 4596: doc-um*
 4597: doc-m*/
 4598: doc-um/mod
 4599: doc-fm/mod
 4600: doc-sm/rem
 4601: 
 4602: 
 4603: @node Floating Point,  , Mixed precision, Arithmetic
 4604: @subsection Floating Point
 4605: @cindex floating point arithmetic words
 4606: 
 4607: For the rules used by the text interpreter for
 4608: recognising floating-point numbers see @ref{Number Conversion}.
 4609: 
 4610: Gforth has a separate floating point stack, but the documentation uses
 4611: the unified notation.@footnote{It's easy to generate the separate
 4612: notation from that by just separating the floating-point numbers out:
 4613: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4614: r3 )}.}
 4615: 
 4616: @cindex floating-point arithmetic, pitfalls
 4617: Floating point numbers have a number of unpleasant surprises for the
 4618: unwary (e.g., floating point addition is not associative) and even a few
 4619: for the wary. You should not use them unless you know what you are doing
 4620: or you don't care that the results you get are totally bogus. If you
 4621: want to learn about the problems of floating point numbers (and how to
 4622: avoid them), you might start with @cite{David Goldberg,
 4623: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4624: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4625: Surveys 23(1):5@minus{}48, March 1991}.
 4626: 
 4627: 
 4628: doc-d>f
 4629: doc-f>d
 4630: doc-f+
 4631: doc-f-
 4632: doc-f*
 4633: doc-f/
 4634: doc-fnegate
 4635: doc-fabs
 4636: doc-fmax
 4637: doc-fmin
 4638: doc-floor
 4639: doc-fround
 4640: doc-f**
 4641: doc-fsqrt
 4642: doc-fexp
 4643: doc-fexpm1
 4644: doc-fln
 4645: doc-flnp1
 4646: doc-flog
 4647: doc-falog
 4648: doc-f2*
 4649: doc-f2/
 4650: doc-1/f
 4651: doc-precision
 4652: doc-set-precision
 4653: 
 4654: @cindex angles in trigonometric operations
 4655: @cindex trigonometric operations
 4656: Angles in floating point operations are given in radians (a full circle
 4657: has 2 pi radians).
 4658: 
 4659: doc-fsin
 4660: doc-fcos
 4661: doc-fsincos
 4662: doc-ftan
 4663: doc-fasin
 4664: doc-facos
 4665: doc-fatan
 4666: doc-fatan2
 4667: doc-fsinh
 4668: doc-fcosh
 4669: doc-ftanh
 4670: doc-fasinh
 4671: doc-facosh
 4672: doc-fatanh
 4673: doc-pi
 4674: 
 4675: @cindex equality of floats
 4676: @cindex floating-point comparisons
 4677: One particular problem with floating-point arithmetic is that comparison
 4678: for equality often fails when you would expect it to succeed.  For this
 4679: reason approximate equality is often preferred (but you still have to
 4680: know what you are doing).  Also note that IEEE NaNs may compare
 4681: differently from what you might expect.  The comparison words are:
 4682: 
 4683: doc-f~rel
 4684: doc-f~abs
 4685: doc-f~
 4686: doc-f=
 4687: doc-f<>
 4688: 
 4689: doc-f<
 4690: doc-f<=
 4691: doc-f>
 4692: doc-f>=
 4693: 
 4694: doc-f0<
 4695: doc-f0<=
 4696: doc-f0<>
 4697: doc-f0=
 4698: doc-f0>
 4699: doc-f0>=
 4700: 
 4701: 
 4702: @node Stack Manipulation, Memory, Arithmetic, Words
 4703: @section Stack Manipulation
 4704: @cindex stack manipulation words
 4705: 
 4706: @cindex floating-point stack in the standard
 4707: Gforth maintains a number of separate stacks:
 4708: 
 4709: @cindex data stack
 4710: @cindex parameter stack
 4711: @itemize @bullet
 4712: @item
 4713: A data stack (also known as the @dfn{parameter stack}) -- for
 4714: characters, cells, addresses, and double cells.
 4715: 
 4716: @cindex floating-point stack
 4717: @item
 4718: A floating point stack -- for holding floating point (FP) numbers.
 4719: 
 4720: @cindex return stack
 4721: @item
 4722: A return stack -- for holding the return addresses of colon
 4723: definitions and other (non-FP) data.
 4724: 
 4725: @cindex locals stack
 4726: @item
 4727: A locals stack -- for holding local variables.
 4728: @end itemize
 4729: 
 4730: @menu
 4731: * Data stack::                  
 4732: * Floating point stack::        
 4733: * Return stack::                
 4734: * Locals stack::                
 4735: * Stack pointer manipulation::  
 4736: @end menu
 4737: 
 4738: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4739: @subsection Data stack
 4740: @cindex data stack manipulation words
 4741: @cindex stack manipulations words, data stack
 4742: 
 4743: 
 4744: doc-drop
 4745: doc-nip
 4746: doc-dup
 4747: doc-over
 4748: doc-tuck
 4749: doc-swap
 4750: doc-pick
 4751: doc-rot
 4752: doc--rot
 4753: doc-?dup
 4754: doc-roll
 4755: doc-2drop
 4756: doc-2nip
 4757: doc-2dup
 4758: doc-2over
 4759: doc-2tuck
 4760: doc-2swap
 4761: doc-2rot
 4762: 
 4763: 
 4764: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4765: @subsection Floating point stack
 4766: @cindex floating-point stack manipulation words
 4767: @cindex stack manipulation words, floating-point stack
 4768: 
 4769: Whilst every sane Forth has a separate floating-point stack, it is not
 4770: strictly required; an ANS Forth system could theoretically keep
 4771: floating-point numbers on the data stack. As an additional difficulty,
 4772: you don't know how many cells a floating-point number takes. It is
 4773: reportedly possible to write words in a way that they work also for a
 4774: unified stack model, but we do not recommend trying it. Instead, just
 4775: say that your program has an environmental dependency on a separate
 4776: floating-point stack.
 4777: 
 4778: doc-floating-stack
 4779: 
 4780: doc-fdrop
 4781: doc-fnip
 4782: doc-fdup
 4783: doc-fover
 4784: doc-ftuck
 4785: doc-fswap
 4786: doc-fpick
 4787: doc-frot
 4788: 
 4789: 
 4790: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4791: @subsection Return stack
 4792: @cindex return stack manipulation words
 4793: @cindex stack manipulation words, return stack
 4794: 
 4795: @cindex return stack and locals
 4796: @cindex locals and return stack
 4797: A Forth system is allowed to keep local variables on the
 4798: return stack. This is reasonable, as local variables usually eliminate
 4799: the need to use the return stack explicitly. So, if you want to produce
 4800: a standard compliant program and you are using local variables in a
 4801: word, forget about return stack manipulations in that word (refer to the
 4802: standard document for the exact rules).
 4803: 
 4804: doc->r
 4805: doc-r>
 4806: doc-r@
 4807: doc-rdrop
 4808: doc-2>r
 4809: doc-2r>
 4810: doc-2r@
 4811: doc-2rdrop
 4812: 
 4813: 
 4814: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4815: @subsection Locals stack
 4816: 
 4817: Gforth uses an extra locals stack.  It is described, along with the
 4818: reasons for its existence, in @ref{Locals implementation}.
 4819: 
 4820: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4821: @subsection Stack pointer manipulation
 4822: @cindex stack pointer manipulation words
 4823: 
 4824: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4825: doc-sp0
 4826: doc-sp@
 4827: doc-sp!
 4828: doc-fp0
 4829: doc-fp@
 4830: doc-fp!
 4831: doc-rp0
 4832: doc-rp@
 4833: doc-rp!
 4834: doc-lp0
 4835: doc-lp@
 4836: doc-lp!
 4837: 
 4838: 
 4839: @node Memory, Control Structures, Stack Manipulation, Words
 4840: @section Memory
 4841: @cindex memory words
 4842: 
 4843: @menu
 4844: * Memory model::                
 4845: * Dictionary allocation::       
 4846: * Heap Allocation::             
 4847: * Memory Access::               
 4848: * Address arithmetic::          
 4849: * Memory Blocks::               
 4850: @end menu
 4851: 
 4852: In addition to the standard Forth memory allocation words, there is also
 4853: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4854: garbage collector}.
 4855: 
 4856: @node Memory model, Dictionary allocation, Memory, Memory
 4857: @subsection ANS Forth and Gforth memory models
 4858: 
 4859: @c The ANS Forth description is a mess (e.g., is the heap part of
 4860: @c the dictionary?), so let's not stick to closely with it.
 4861: 
 4862: ANS Forth considers a Forth system as consisting of several address
 4863: spaces, of which only @dfn{data space} is managed and accessible with
 4864: the memory words.  Memory not necessarily in data space includes the
 4865: stacks, the code (called code space) and the headers (called name
 4866: space). In Gforth everything is in data space, but the code for the
 4867: primitives is usually read-only.
 4868: 
 4869: Data space is divided into a number of areas: The (data space portion of
 4870: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 4871: refer to the search data structure embodied in word lists and headers,
 4872: because it is used for looking up names, just as you would in a
 4873: conventional dictionary.}, the heap, and a number of system-allocated
 4874: buffers.
 4875: 
 4876: @cindex address arithmetic restrictions, ANS vs. Gforth
 4877: @cindex contiguous regions, ANS vs. Gforth
 4878: In ANS Forth data space is also divided into contiguous regions.  You
 4879: can only use address arithmetic within a contiguous region, not between
 4880: them.  Usually each allocation gives you one contiguous region, but the
 4881: dictionary allocation words have additional rules (@pxref{Dictionary
 4882: allocation}).
 4883: 
 4884: Gforth provides one big address space, and address arithmetic can be
 4885: performed between any addresses. However, in the dictionary headers or
 4886: code are interleaved with data, so almost the only contiguous data space
 4887: regions there are those described by ANS Forth as contiguous; but you
 4888: can be sure that the dictionary is allocated towards increasing
 4889: addresses even between contiguous regions.  The memory order of
 4890: allocations in the heap is platform-dependent (and possibly different
 4891: from one run to the next).
 4892: 
 4893: 
 4894: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 4895: @subsection Dictionary allocation
 4896: @cindex reserving data space
 4897: @cindex data space - reserving some
 4898: 
 4899: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 4900: you want to deallocate X, you also deallocate everything
 4901: allocated after X.
 4902: 
 4903: @cindex contiguous regions in dictionary allocation
 4904: The allocations using the words below are contiguous and grow the region
 4905: towards increasing addresses.  Other words that allocate dictionary
 4906: memory of any kind (i.e., defining words including @code{:noname}) end
 4907: the contiguous region and start a new one.
 4908: 
 4909: In ANS Forth only @code{create}d words are guaranteed to produce an
 4910: address that is the start of the following contiguous region.  In
 4911: particular, the cell allocated by @code{variable} is not guaranteed to
 4912: be contiguous with following @code{allot}ed memory.
 4913: 
 4914: You can deallocate memory by using @code{allot} with a negative argument
 4915: (with some restrictions, see @code{allot}). For larger deallocations use
 4916: @code{marker}.
 4917: 
 4918: 
 4919: doc-here
 4920: doc-unused
 4921: doc-allot
 4922: doc-c,
 4923: doc-f,
 4924: doc-,
 4925: doc-2,
 4926: 
 4927: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 4928: course you should allocate memory in an aligned way, too. I.e., before
 4929: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 4930: The words below align @code{here} if it is not already.  Basically it is
 4931: only already aligned for a type, if the last allocation was a multiple
 4932: of the size of this type and if @code{here} was aligned for this type
 4933: before.
 4934: 
 4935: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 4936: ANS Forth (@code{maxalign}ed in Gforth).
 4937: 
 4938: doc-align
 4939: doc-falign
 4940: doc-sfalign
 4941: doc-dfalign
 4942: doc-maxalign
 4943: doc-cfalign
 4944: 
 4945: 
 4946: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 4947: @subsection Heap allocation
 4948: @cindex heap allocation
 4949: @cindex dynamic allocation of memory
 4950: @cindex memory-allocation word set
 4951: 
 4952: @cindex contiguous regions and heap allocation
 4953: Heap allocation supports deallocation of allocated memory in any
 4954: order. Dictionary allocation is not affected by it (i.e., it does not
 4955: end a contiguous region). In Gforth, these words are implemented using
 4956: the standard C library calls malloc(), free() and resize().
 4957: 
 4958: The memory region produced by one invocation of @code{allocate} or
 4959: @code{resize} is internally contiguous.  There is no contiguity between
 4960: such a region and any other region (including others allocated from the
 4961: heap).
 4962: 
 4963: doc-allocate
 4964: doc-free
 4965: doc-resize
 4966: 
 4967: 
 4968: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 4969: @subsection Memory Access
 4970: @cindex memory access words
 4971: 
 4972: doc-@
 4973: doc-!
 4974: doc-+!
 4975: doc-c@
 4976: doc-c!
 4977: doc-2@
 4978: doc-2!
 4979: doc-f@
 4980: doc-f!
 4981: doc-sf@
 4982: doc-sf!
 4983: doc-df@
 4984: doc-df!
 4985: 
 4986: 
 4987: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 4988: @subsection Address arithmetic
 4989: @cindex address arithmetic words
 4990: 
 4991: Address arithmetic is the foundation on which you can build data
 4992: structures like arrays, records (@pxref{Structures}) and objects
 4993: (@pxref{Object-oriented Forth}).
 4994: 
 4995: @cindex address unit
 4996: @cindex au (address unit)
 4997: ANS Forth does not specify the sizes of the data types. Instead, it
 4998: offers a number of words for computing sizes and doing address
 4999: arithmetic. Address arithmetic is performed in terms of address units
 5000: (aus); on most systems the address unit is one byte. Note that a
 5001: character may have more than one au, so @code{chars} is no noop (on
 5002: platforms where it is a noop, it compiles to nothing).
 5003: 
 5004: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5005: you have the address of a cell, perform @code{1 cells +}, and you will
 5006: have the address of the next cell.
 5007: 
 5008: @cindex contiguous regions and address arithmetic
 5009: In ANS Forth you can perform address arithmetic only within a contiguous
 5010: region, i.e., if you have an address into one region, you can only add
 5011: and subtract such that the result is still within the region; you can
 5012: only subtract or compare addresses from within the same contiguous
 5013: region.  Reasons: several contiguous regions can be arranged in memory
 5014: in any way; on segmented systems addresses may have unusual
 5015: representations, such that address arithmetic only works within a
 5016: region.  Gforth provides a few more guarantees (linear address space,
 5017: dictionary grows upwards), but in general I have found it easy to stay
 5018: within contiguous regions (exception: computing and comparing to the
 5019: address just beyond the end of an array).
 5020: 
 5021: @cindex alignment of addresses for types
 5022: ANS Forth also defines words for aligning addresses for specific
 5023: types. Many computers require that accesses to specific data types
 5024: must only occur at specific addresses; e.g., that cells may only be
 5025: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5026: accesses, it can usually perform aligned accesses faster. 
 5027: 
 5028: For the performance-conscious: alignment operations are usually only
 5029: necessary during the definition of a data structure, not during the
 5030: (more frequent) accesses to it.
 5031: 
 5032: ANS Forth defines no words for character-aligning addresses. This is not
 5033: an oversight, but reflects the fact that addresses that are not
 5034: char-aligned have no use in the standard and therefore will not be
 5035: created.
 5036: 
 5037: @cindex @code{CREATE} and alignment
 5038: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5039: are cell-aligned; in addition, Gforth guarantees that these addresses
 5040: are aligned for all purposes.
 5041: 
 5042: Note that the ANS Forth word @code{char} has nothing to do with address
 5043: arithmetic.
 5044: 
 5045: 
 5046: doc-chars
 5047: doc-char+
 5048: doc-cells
 5049: doc-cell+
 5050: doc-cell
 5051: doc-aligned
 5052: doc-floats
 5053: doc-float+
 5054: doc-float
 5055: doc-faligned
 5056: doc-sfloats
 5057: doc-sfloat+
 5058: doc-sfaligned
 5059: doc-dfloats
 5060: doc-dfloat+
 5061: doc-dfaligned
 5062: doc-maxaligned
 5063: doc-cfaligned
 5064: doc-address-unit-bits
 5065: 
 5066: 
 5067: @node Memory Blocks,  , Address arithmetic, Memory
 5068: @subsection Memory Blocks
 5069: @cindex memory block words
 5070: @cindex character strings - moving and copying
 5071: 
 5072: Memory blocks often represent character strings; For ways of storing
 5073: character strings in memory see @ref{String Formats}.  For other
 5074: string-processing words see @ref{Displaying characters and strings}.
 5075: 
 5076: A few of these words work on address unit blocks.  In that case, you
 5077: usually have to insert @code{CHARS} before the word when working on
 5078: character strings.  Most words work on character blocks, and expect a
 5079: char-aligned address.
 5080: 
 5081: When copying characters between overlapping memory regions, use
 5082: @code{chars move} or choose carefully between @code{cmove} and
 5083: @code{cmove>}.
 5084: 
 5085: doc-move
 5086: doc-erase
 5087: doc-cmove
 5088: doc-cmove>
 5089: doc-fill
 5090: doc-blank
 5091: doc-compare
 5092: doc-str=
 5093: doc-str<
 5094: doc-string-prefix?
 5095: doc-search
 5096: doc--trailing
 5097: doc-/string
 5098: doc-bounds
 5099: 
 5100: 
 5101: @comment TODO examples
 5102: 
 5103: 
 5104: @node Control Structures, Defining Words, Memory, Words
 5105: @section Control Structures
 5106: @cindex control structures
 5107: 
 5108: Control structures in Forth cannot be used interpretively, only in a
 5109: colon definition@footnote{To be precise, they have no interpretation
 5110: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5111: not like this limitation, but have not seen a satisfying way around it
 5112: yet, although many schemes have been proposed.
 5113: 
 5114: @menu
 5115: * Selection::                   IF ... ELSE ... ENDIF
 5116: * Simple Loops::                BEGIN ...
 5117: * Counted Loops::               DO
 5118: * Arbitrary control structures::  
 5119: * Calls and returns::           
 5120: * Exception Handling::          
 5121: @end menu
 5122: 
 5123: @node Selection, Simple Loops, Control Structures, Control Structures
 5124: @subsection Selection
 5125: @cindex selection control structures
 5126: @cindex control structures for selection
 5127: 
 5128: @cindex @code{IF} control structure
 5129: @example
 5130: @i{flag}
 5131: IF
 5132:   @i{code}
 5133: ENDIF
 5134: @end example
 5135: @noindent
 5136: 
 5137: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5138: with any bit set represents truth) @i{code} is executed.
 5139: 
 5140: @example
 5141: @i{flag}
 5142: IF
 5143:   @i{code1}
 5144: ELSE
 5145:   @i{code2}
 5146: ENDIF
 5147: @end example
 5148: 
 5149: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5150: executed.
 5151: 
 5152: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5153: standard, and @code{ENDIF} is not, although it is quite popular. We
 5154: recommend using @code{ENDIF}, because it is less confusing for people
 5155: who also know other languages (and is not prone to reinforcing negative
 5156: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5157: system that only supplies @code{THEN} is simple:
 5158: @example
 5159: : ENDIF   POSTPONE then ; immediate
 5160: @end example
 5161: 
 5162: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5163: (adv.)}  has the following meanings:
 5164: @quotation
 5165: ... 2b: following next after in order ... 3d: as a necessary consequence
 5166: (if you were there, then you saw them).
 5167: @end quotation
 5168: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5169: and many other programming languages has the meaning 3d.]
 5170: 
 5171: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5172: you can avoid using @code{?dup}. Using these alternatives is also more
 5173: efficient than using @code{?dup}. Definitions in ANS Forth
 5174: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5175: @file{compat/control.fs}.
 5176: 
 5177: @cindex @code{CASE} control structure
 5178: @example
 5179: @i{n}
 5180: CASE
 5181:   @i{n1} OF @i{code1} ENDOF
 5182:   @i{n2} OF @i{code2} ENDOF
 5183:   @dots{}
 5184:   ( n ) @i{default-code} ( n )
 5185: ENDCASE ( )
 5186: @end example
 5187: 
 5188: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
 5189: no @i{ni} matches, the optional @i{default-code} is executed. The
 5190: optional default case can be added by simply writing the code after
 5191: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
 5192: but must not consume it.  The value @i{n} is consumed by this
 5193: construction (either by a OF that matches, or by the ENDCASE, if no OF
 5194: matches).
 5195: 
 5196: @progstyle
 5197: To keep the code understandable, you should ensure that you change the
 5198: stack in the same way (wrt. number and types of stack items consumed
 5199: and pushed) on all paths through a selection construct.
 5200: 
 5201: @node Simple Loops, Counted Loops, Selection, Control Structures
 5202: @subsection Simple Loops
 5203: @cindex simple loops
 5204: @cindex loops without count 
 5205: 
 5206: @cindex @code{WHILE} loop
 5207: @example
 5208: BEGIN
 5209:   @i{code1}
 5210:   @i{flag}
 5211: WHILE
 5212:   @i{code2}
 5213: REPEAT
 5214: @end example
 5215: 
 5216: @i{code1} is executed and @i{flag} is computed. If it is true,
 5217: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5218: false, execution continues after the @code{REPEAT}.
 5219: 
 5220: @cindex @code{UNTIL} loop
 5221: @example
 5222: BEGIN
 5223:   @i{code}
 5224:   @i{flag}
 5225: UNTIL
 5226: @end example
 5227: 
 5228: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5229: 
 5230: @progstyle
 5231: To keep the code understandable, a complete iteration of the loop should
 5232: not change the number and types of the items on the stacks.
 5233: 
 5234: @cindex endless loop
 5235: @cindex loops, endless
 5236: @example
 5237: BEGIN
 5238:   @i{code}
 5239: AGAIN
 5240: @end example
 5241: 
 5242: This is an endless loop.
 5243: 
 5244: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5245: @subsection Counted Loops
 5246: @cindex counted loops
 5247: @cindex loops, counted
 5248: @cindex @code{DO} loops
 5249: 
 5250: The basic counted loop is:
 5251: @example
 5252: @i{limit} @i{start}
 5253: ?DO
 5254:   @i{body}
 5255: LOOP
 5256: @end example
 5257: 
 5258: This performs one iteration for every integer, starting from @i{start}
 5259: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5260: accessed with @code{i}. For example, the loop:
 5261: @example
 5262: 10 0 ?DO
 5263:   i .
 5264: LOOP
 5265: @end example
 5266: @noindent
 5267: prints @code{0 1 2 3 4 5 6 7 8 9}
 5268: 
 5269: The index of the innermost loop can be accessed with @code{i}, the index
 5270: of the next loop with @code{j}, and the index of the third loop with
 5271: @code{k}.
 5272: 
 5273: 
 5274: doc-i
 5275: doc-j
 5276: doc-k
 5277: 
 5278: 
 5279: The loop control data are kept on the return stack, so there are some
 5280: restrictions on mixing return stack accesses and counted loop words. In
 5281: particuler, if you put values on the return stack outside the loop, you
 5282: cannot read them inside the loop@footnote{well, not in a way that is
 5283: portable.}. If you put values on the return stack within a loop, you
 5284: have to remove them before the end of the loop and before accessing the
 5285: index of the loop.
 5286: 
 5287: There are several variations on the counted loop:
 5288: 
 5289: @itemize @bullet
 5290: @item
 5291: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5292: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5293: 
 5294: @example
 5295: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5296: @end example
 5297: prints @code{0 1 2 3}
 5298: 
 5299: 
 5300: @item
 5301: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5302: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5303: return stack so @code{EXIT} can get to its return address. For example:
 5304: 
 5305: @example
 5306: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5307: @end example
 5308: prints @code{0 1 2 3}
 5309: 
 5310: 
 5311: @item
 5312: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5313: (and @code{LOOP} iterates until they become equal by wrap-around
 5314: arithmetic). This behaviour is usually not what you want. Therefore,
 5315: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5316: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5317: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5318: unsigned loop parameters.
 5319: 
 5320: @item
 5321: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5322: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5323: if you know that the loop is entered in any case. Such knowledge tends
 5324: to become invalid during maintenance of a program, and then the
 5325: @code{DO} will make trouble.
 5326: 
 5327: @item
 5328: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5329: index by @i{n} instead of by 1. The loop is terminated when the border
 5330: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5331: 
 5332: @example
 5333: 4 0 +DO  i .  2 +LOOP
 5334: @end example
 5335: @noindent
 5336: prints @code{0 2}
 5337: 
 5338: @example
 5339: 4 1 +DO  i .  2 +LOOP
 5340: @end example
 5341: @noindent
 5342: prints @code{1 3}
 5343: 
 5344: @item
 5345: @cindex negative increment for counted loops
 5346: @cindex counted loops with negative increment
 5347: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5348: 
 5349: @example
 5350: -1 0 ?DO  i .  -1 +LOOP
 5351: @end example
 5352: @noindent
 5353: prints @code{0 -1}
 5354: 
 5355: @example
 5356: 0 0 ?DO  i .  -1 +LOOP
 5357: @end example
 5358: prints nothing.
 5359: 
 5360: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5361: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5362: index by @i{u} each iteration. The loop is terminated when the border
 5363: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5364: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5365: 
 5366: @example
 5367: -2 0 -DO  i .  1 -LOOP
 5368: @end example
 5369: @noindent
 5370: prints @code{0 -1}
 5371: 
 5372: @example
 5373: -1 0 -DO  i .  1 -LOOP
 5374: @end example
 5375: @noindent
 5376: prints @code{0}
 5377: 
 5378: @example
 5379: 0 0 -DO  i .  1 -LOOP
 5380: @end example
 5381: @noindent
 5382: prints nothing.
 5383: 
 5384: @end itemize
 5385: 
 5386: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5387: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5388: for these words that uses only standard words is provided in
 5389: @file{compat/loops.fs}.
 5390: 
 5391: 
 5392: @cindex @code{FOR} loops
 5393: Another counted loop is:
 5394: @example
 5395: @i{n}
 5396: FOR
 5397:   @i{body}
 5398: NEXT
 5399: @end example
 5400: This is the preferred loop of native code compiler writers who are too
 5401: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5402: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5403: @code{i} produces values starting with @i{n} and ending with 0. Other
 5404: Forth systems may behave differently, even if they support @code{FOR}
 5405: loops. To avoid problems, don't use @code{FOR} loops.
 5406: 
 5407: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5408: @subsection Arbitrary control structures
 5409: @cindex control structures, user-defined
 5410: 
 5411: @cindex control-flow stack
 5412: ANS Forth permits and supports using control structures in a non-nested
 5413: way. Information about incomplete control structures is stored on the
 5414: control-flow stack. This stack may be implemented on the Forth data
 5415: stack, and this is what we have done in Gforth.
 5416: 
 5417: @cindex @code{orig}, control-flow stack item
 5418: @cindex @code{dest}, control-flow stack item
 5419: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5420: entry represents a backward branch target. A few words are the basis for
 5421: building any control structure possible (except control structures that
 5422: need storage, like calls, coroutines, and backtracking).
 5423: 
 5424: 
 5425: doc-if
 5426: doc-ahead
 5427: doc-then
 5428: doc-begin
 5429: doc-until
 5430: doc-again
 5431: doc-cs-pick
 5432: doc-cs-roll
 5433: 
 5434: 
 5435: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5436: manipulate the control-flow stack in a portable way. Without them, you
 5437: would need to know how many stack items are occupied by a control-flow
 5438: entry (many systems use one cell. In Gforth they currently take three,
 5439: but this may change in the future).
 5440: 
 5441: Some standard control structure words are built from these words:
 5442: 
 5443: 
 5444: doc-else
 5445: doc-while
 5446: doc-repeat
 5447: 
 5448: 
 5449: @noindent
 5450: Gforth adds some more control-structure words:
 5451: 
 5452: 
 5453: doc-endif
 5454: doc-?dup-if
 5455: doc-?dup-0=-if
 5456: 
 5457: 
 5458: @noindent
 5459: Counted loop words constitute a separate group of words:
 5460: 
 5461: 
 5462: doc-?do
 5463: doc-+do
 5464: doc-u+do
 5465: doc--do
 5466: doc-u-do
 5467: doc-do
 5468: doc-for
 5469: doc-loop
 5470: doc-+loop
 5471: doc--loop
 5472: doc-next
 5473: doc-leave
 5474: doc-?leave
 5475: doc-unloop
 5476: doc-done
 5477: 
 5478: 
 5479: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5480: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5481: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5482: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5483: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5484: resolved (by using one of the loop-ending words or @code{DONE}).
 5485: 
 5486: @noindent
 5487: Another group of control structure words are:
 5488: 
 5489: 
 5490: doc-case
 5491: doc-endcase
 5492: doc-of
 5493: doc-endof
 5494: 
 5495: 
 5496: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5497: @code{CS-ROLL}.
 5498: 
 5499: @subsubsection Programming Style
 5500: @cindex control structures programming style
 5501: @cindex programming style, arbitrary control structures
 5502: 
 5503: In order to ensure readability we recommend that you do not create
 5504: arbitrary control structures directly, but define new control structure
 5505: words for the control structure you want and use these words in your
 5506: program. For example, instead of writing:
 5507: 
 5508: @example
 5509: BEGIN
 5510:   ...
 5511: IF [ 1 CS-ROLL ]
 5512:   ...
 5513: AGAIN THEN
 5514: @end example
 5515: 
 5516: @noindent
 5517: we recommend defining control structure words, e.g.,
 5518: 
 5519: @example
 5520: : WHILE ( DEST -- ORIG DEST )
 5521:  POSTPONE IF
 5522:  1 CS-ROLL ; immediate
 5523: 
 5524: : REPEAT ( orig dest -- )
 5525:  POSTPONE AGAIN
 5526:  POSTPONE THEN ; immediate
 5527: @end example
 5528: 
 5529: @noindent
 5530: and then using these to create the control structure:
 5531: 
 5532: @example
 5533: BEGIN
 5534:   ...
 5535: WHILE
 5536:   ...
 5537: REPEAT
 5538: @end example
 5539: 
 5540: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5541: @code{WHILE} are predefined, so in this example it would not be
 5542: necessary to define them.
 5543: 
 5544: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5545: @subsection Calls and returns
 5546: @cindex calling a definition
 5547: @cindex returning from a definition
 5548: 
 5549: @cindex recursive definitions
 5550: A definition can be called simply be writing the name of the definition
 5551: to be called. Normally a definition is invisible during its own
 5552: definition. If you want to write a directly recursive definition, you
 5553: can use @code{recursive} to make the current definition visible, or
 5554: @code{recurse} to call the current definition directly.
 5555: 
 5556: 
 5557: doc-recursive
 5558: doc-recurse
 5559: 
 5560: 
 5561: @comment TODO add example of the two recursion methods
 5562: @quotation
 5563: @progstyle
 5564: I prefer using @code{recursive} to @code{recurse}, because calling the
 5565: definition by name is more descriptive (if the name is well-chosen) than
 5566: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5567: implementation, it is much better to read (and think) ``now sort the
 5568: partitions'' than to read ``now do a recursive call''.
 5569: @end quotation
 5570: 
 5571: For mutual recursion, use @code{Defer}red words, like this:
 5572: 
 5573: @example
 5574: Defer foo
 5575: 
 5576: : bar ( ... -- ... )
 5577:  ... foo ... ;
 5578: 
 5579: :noname ( ... -- ... )
 5580:  ... bar ... ;
 5581: IS foo
 5582: @end example
 5583: 
 5584: Deferred words are discussed in more detail in @ref{Deferred words}.
 5585: 
 5586: The current definition returns control to the calling definition when
 5587: the end of the definition is reached or @code{EXIT} is encountered.
 5588: 
 5589: doc-exit
 5590: doc-;s
 5591: 
 5592: 
 5593: @node Exception Handling,  , Calls and returns, Control Structures
 5594: @subsection Exception Handling
 5595: @cindex exceptions
 5596: 
 5597: @c quit is a very bad idea for error handling, 
 5598: @c because it does not translate into a THROW
 5599: @c it also does not belong into this chapter
 5600: 
 5601: If a word detects an error condition that it cannot handle, it can
 5602: @code{throw} an exception.  In the simplest case, this will terminate
 5603: your program, and report an appropriate error.
 5604: 
 5605: doc-throw
 5606: 
 5607: @code{Throw} consumes a cell-sized error number on the stack. There are
 5608: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5609: Gforth (and most other systems) you can use the iors produced by various
 5610: words as error numbers (e.g., a typical use of @code{allocate} is
 5611: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5612: to define your own error numbers (with decent error reporting); an ANS
 5613: Forth version of this word (but without the error messages) is available
 5614: in @code{compat/except.fs}.  And finally, you can use your own error
 5615: numbers (anything outside the range -4095..0), but won't get nice error
 5616: messages, only numbers.  For example, try:
 5617: 
 5618: @example
 5619: -10 throw                    \ ANS defined
 5620: -267 throw                   \ system defined
 5621: s" my error" exception throw \ user defined
 5622: 7 throw                      \ arbitrary number
 5623: @end example
 5624: 
 5625: doc---exception-exception
 5626: 
 5627: A common idiom to @code{THROW} a specific error if a flag is true is
 5628: this:
 5629: 
 5630: @example
 5631: @code{( flag ) 0<> @i{errno} and throw}
 5632: @end example
 5633: 
 5634: Your program can provide exception handlers to catch exceptions.  An
 5635: exception handler can be used to correct the problem, or to clean up
 5636: some data structures and just throw the exception to the next exception
 5637: handler.  Note that @code{throw} jumps to the dynamically innermost
 5638: exception handler.  The system's exception handler is outermost, and just
 5639: prints an error and restarts command-line interpretation (or, in batch
 5640: mode (i.e., while processing the shell command line), leaves Gforth).
 5641: 
 5642: The ANS Forth way to catch exceptions is @code{catch}:
 5643: 
 5644: doc-catch
 5645: 
 5646: The most common use of exception handlers is to clean up the state when
 5647: an error happens.  E.g.,
 5648: 
 5649: @example
 5650: base @ >r hex \ actually the hex should be inside foo, or we h
 5651: ['] foo catch ( nerror|0 )
 5652: r> base !
 5653: ( nerror|0 ) throw \ pass it on
 5654: @end example
 5655: 
 5656: A use of @code{catch} for handling the error @code{myerror} might look
 5657: like this:
 5658: 
 5659: @example
 5660: ['] foo catch
 5661: CASE
 5662:   myerror OF ... ( do something about it ) ENDOF
 5663:   dup throw \ default: pass other errors on, do nothing on non-errors
 5664: ENDCASE
 5665: @end example
 5666: 
 5667: Having to wrap the code into a separate word is often cumbersome,
 5668: therefore Gforth provides an alternative syntax:
 5669: 
 5670: @example
 5671: TRY
 5672:   @i{code1}
 5673: RECOVER     \ optional
 5674:   @i{code2} \ optional
 5675: ENDTRY
 5676: @end example
 5677: 
 5678: This performs @i{Code1}.  If @i{code1} completes normally, execution
 5679: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
 5680: reset to the state during @code{try}, the throw value is pushed on the
 5681: data stack, and execution constinues at @i{code2}, and finally falls
 5682: through the @code{endtry} into the following code.
 5683: 
 5684: doc-try
 5685: doc-recover
 5686: doc-endtry
 5687: 
 5688: The cleanup example from above in this syntax:
 5689: 
 5690: @example
 5691: base @ >r TRY
 5692:   hex foo \ now the hex is placed correctly
 5693:   0       \ value for throw
 5694: RECOVER ENDTRY
 5695: r> base ! throw
 5696: @end example
 5697: 
 5698: And here's the error handling example:
 5699: 
 5700: @example
 5701: TRY
 5702:   foo
 5703: RECOVER
 5704:   CASE
 5705:     myerror OF ... ( do something about it ) ENDOF
 5706:     throw \ pass other errors on
 5707:   ENDCASE
 5708: ENDTRY
 5709: @end example
 5710: 
 5711: @progstyle
 5712: As usual, you should ensure that the stack depth is statically known at
 5713: the end: either after the @code{throw} for passing on errors, or after
 5714: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5715: selection construct for handling the error).
 5716: 
 5717: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5718: and you can provide an error message.  @code{Abort} just produces an
 5719: ``Aborted'' error.
 5720: 
 5721: The problem with these words is that exception handlers cannot
 5722: differentiate between different @code{abort"}s; they just look like
 5723: @code{-2 throw} to them (the error message cannot be accessed by
 5724: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5725: exception handlers.
 5726: 
 5727: doc-abort"
 5728: doc-abort
 5729: 
 5730: 
 5731: 
 5732: @c -------------------------------------------------------------
 5733: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5734: @section Defining Words
 5735: @cindex defining words
 5736: 
 5737: Defining words are used to extend Forth by creating new entries in the dictionary.
 5738: 
 5739: @menu
 5740: * CREATE::                      
 5741: * Variables::                   Variables and user variables
 5742: * Constants::                   
 5743: * Values::                      Initialised variables
 5744: * Colon Definitions::           
 5745: * Anonymous Definitions::       Definitions without names
 5746: * Supplying names::             Passing definition names as strings
 5747: * User-defined Defining Words::  
 5748: * Deferred words::              Allow forward references
 5749: * Aliases::                     
 5750: @end menu
 5751: 
 5752: @node CREATE, Variables, Defining Words, Defining Words
 5753: @subsection @code{CREATE}
 5754: @cindex simple defining words
 5755: @cindex defining words, simple
 5756: 
 5757: Defining words are used to create new entries in the dictionary. The
 5758: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5759: this:
 5760: 
 5761: @example
 5762: CREATE new-word1
 5763: @end example
 5764: 
 5765: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5766: input stream (@code{new-word1} in our example).  It generates a
 5767: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5768: executed, all that it does is leave an address on the stack. The address
 5769: represents the value of the data space pointer (@code{HERE}) at the time
 5770: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5771: associating a name with the address of a region of memory.
 5772: 
 5773: doc-create
 5774: 
 5775: Note that in ANS Forth guarantees only for @code{create} that its body
 5776: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5777: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5778: @code{create}d words can be modified with @code{does>}
 5779: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5780: can only be applied to @code{create}d words.
 5781: 
 5782: By extending this example to reserve some memory in data space, we end
 5783: up with something like a @i{variable}. Here are two different ways to do
 5784: it:
 5785: 
 5786: @example
 5787: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5788: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 5789: @end example
 5790: 
 5791: The variable can be examined and modified using @code{@@} (``fetch'') and
 5792: @code{!} (``store'') like this:
 5793: 
 5794: @example
 5795: new-word2 @@ .      \ get address, fetch from it and display
 5796: 1234 new-word2 !   \ new value, get address, store to it
 5797: @end example
 5798: 
 5799: @cindex arrays
 5800: A similar mechanism can be used to create arrays. For example, an
 5801: 80-character text input buffer:
 5802: 
 5803: @example
 5804: CREATE text-buf 80 chars allot
 5805: 
 5806: text-buf 0 chars c@@ \ the 1st character (offset 0)
 5807: text-buf 3 chars c@@ \ the 4th character (offset 3)
 5808: @end example
 5809: 
 5810: You can build arbitrarily complex data structures by allocating
 5811: appropriate areas of memory. For further discussions of this, and to
 5812: learn about some Gforth tools that make it easier,
 5813: @xref{Structures}.
 5814: 
 5815: 
 5816: @node Variables, Constants, CREATE, Defining Words
 5817: @subsection Variables
 5818: @cindex variables
 5819: 
 5820: The previous section showed how a sequence of commands could be used to
 5821: generate a variable.  As a final refinement, the whole code sequence can
 5822: be wrapped up in a defining word (pre-empting the subject of the next
 5823: section), making it easier to create new variables:
 5824: 
 5825: @example
 5826: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 5827: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 5828: 
 5829: myvariableX foo \ variable foo starts off with an unknown value
 5830: myvariable0 joe \ whilst joe is initialised to 0
 5831: 
 5832: 45 3 * foo !   \ set foo to 135
 5833: 1234 joe !     \ set joe to 1234
 5834: 3 joe +!       \ increment joe by 3.. to 1237
 5835: @end example
 5836: 
 5837: Not surprisingly, there is no need to define @code{myvariable}, since
 5838: Forth already has a definition @code{Variable}. ANS Forth does not
 5839: guarantee that a @code{Variable} is initialised when it is created
 5840: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 5841: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 5842: like @code{myvariable0}). Forth also provides @code{2Variable} and
 5843: @code{fvariable} for double and floating-point variables, respectively
 5844: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 5845: store a boolean, you can use @code{on} and @code{off} to toggle its
 5846: state.
 5847: 
 5848: doc-variable
 5849: doc-2variable
 5850: doc-fvariable
 5851: 
 5852: @cindex user variables
 5853: @cindex user space
 5854: The defining word @code{User} behaves in the same way as @code{Variable}.
 5855: The difference is that it reserves space in @i{user (data) space} rather
 5856: than normal data space. In a Forth system that has a multi-tasker, each
 5857: task has its own set of user variables.
 5858: 
 5859: doc-user
 5860: @c doc-udp
 5861: @c doc-uallot
 5862: 
 5863: @comment TODO is that stuff about user variables strictly correct? Is it
 5864: @comment just terminal tasks that have user variables?
 5865: @comment should document tasker.fs (with some examples) elsewhere
 5866: @comment in this manual, then expand on user space and user variables.
 5867: 
 5868: @node Constants, Values, Variables, Defining Words
 5869: @subsection Constants
 5870: @cindex constants
 5871: 
 5872: @code{Constant} allows you to declare a fixed value and refer to it by
 5873: name. For example:
 5874: 
 5875: @example
 5876: 12 Constant INCHES-PER-FOOT
 5877: 3E+08 fconstant SPEED-O-LIGHT
 5878: @end example
 5879: 
 5880: A @code{Variable} can be both read and written, so its run-time
 5881: behaviour is to supply an address through which its current value can be
 5882: manipulated. In contrast, the value of a @code{Constant} cannot be
 5883: changed once it has been declared@footnote{Well, often it can be -- but
 5884: not in a Standard, portable way. It's safer to use a @code{Value} (read
 5885: on).} so it's not necessary to supply the address -- it is more
 5886: efficient to return the value of the constant directly. That's exactly
 5887: what happens; the run-time effect of a constant is to put its value on
 5888: the top of the stack (You can find one
 5889: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 5890: 
 5891: Forth also provides @code{2Constant} and @code{fconstant} for defining
 5892: double and floating-point constants, respectively.
 5893: 
 5894: doc-constant
 5895: doc-2constant
 5896: doc-fconstant
 5897: 
 5898: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 5899: @c nac-> How could that not be true in an ANS Forth? You can't define a
 5900: @c constant, use it and then delete the definition of the constant..
 5901: 
 5902: @c anton->An ANS Forth system can compile a constant to a literal; On
 5903: @c decompilation you would see only the number, just as if it had been used
 5904: @c in the first place.  The word will stay, of course, but it will only be
 5905: @c used by the text interpreter (no run-time duties, except when it is 
 5906: @c POSTPONEd or somesuch).
 5907: 
 5908: @c nac:
 5909: @c I agree that it's rather deep, but IMO it is an important difference
 5910: @c relative to other programming languages.. often it's annoying: it
 5911: @c certainly changes my programming style relative to C.
 5912: 
 5913: @c anton: In what way?
 5914: 
 5915: Constants in Forth behave differently from their equivalents in other
 5916: programming languages. In other languages, a constant (such as an EQU in
 5917: assembler or a #define in C) only exists at compile-time; in the
 5918: executable program the constant has been translated into an absolute
 5919: number and, unless you are using a symbolic debugger, it's impossible to
 5920: know what abstract thing that number represents. In Forth a constant has
 5921: an entry in the header space and remains there after the code that uses
 5922: it has been defined. In fact, it must remain in the dictionary since it
 5923: has run-time duties to perform. For example:
 5924: 
 5925: @example
 5926: 12 Constant INCHES-PER-FOOT
 5927: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 5928: @end example
 5929: 
 5930: @cindex in-lining of constants
 5931: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 5932: associated with the constant @code{INCHES-PER-FOOT}. If you use
 5933: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 5934: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 5935: attempt to optimise constants by in-lining them where they are used. You
 5936: can force Gforth to in-line a constant like this:
 5937: 
 5938: @example
 5939: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 5940: @end example
 5941: 
 5942: If you use @code{see} to decompile @i{this} version of
 5943: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 5944: longer present. To understand how this works, read
 5945: @ref{Interpret/Compile states}, and @ref{Literals}.
 5946: 
 5947: In-lining constants in this way might improve execution time
 5948: fractionally, and can ensure that a constant is now only referenced at
 5949: compile-time. However, the definition of the constant still remains in
 5950: the dictionary. Some Forth compilers provide a mechanism for controlling
 5951: a second dictionary for holding transient words such that this second
 5952: dictionary can be deleted later in order to recover memory
 5953: space. However, there is no standard way of doing this.
 5954: 
 5955: 
 5956: @node Values, Colon Definitions, Constants, Defining Words
 5957: @subsection Values
 5958: @cindex values
 5959: 
 5960: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 5961: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 5962: (not in ANS Forth) you can access (and change) a @code{value} also with
 5963: @code{>body}.
 5964: 
 5965: Here are some
 5966: examples:
 5967: 
 5968: @example
 5969: 12 Value APPLES     \ Define APPLES with an initial value of 12
 5970: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 5971: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 5972: APPLES              \ puts 35 on the top of the stack.
 5973: @end example
 5974: 
 5975: doc-value
 5976: doc-to
 5977: 
 5978: 
 5979: 
 5980: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 5981: @subsection Colon Definitions
 5982: @cindex colon definitions
 5983: 
 5984: @example
 5985: : name ( ... -- ... )
 5986:     word1 word2 word3 ;
 5987: @end example
 5988: 
 5989: @noindent
 5990: Creates a word called @code{name} that, upon execution, executes
 5991: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 5992: 
 5993: The explanation above is somewhat superficial. For simple examples of
 5994: colon definitions see @ref{Your first definition}.  For an in-depth
 5995: discussion of some of the issues involved, @xref{Interpretation and
 5996: Compilation Semantics}.
 5997: 
 5998: doc-:
 5999: doc-;
 6000: 
 6001: 
 6002: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 6003: @subsection Anonymous Definitions
 6004: @cindex colon definitions
 6005: @cindex defining words without name
 6006: 
 6007: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6008: name. You can do this with:
 6009: 
 6010: doc-:noname
 6011: 
 6012: This leaves the execution token for the word on the stack after the
 6013: closing @code{;}. Here's an example in which a deferred word is
 6014: initialised with an @code{xt} from an anonymous colon definition:
 6015: 
 6016: @example
 6017: Defer deferred
 6018: :noname ( ... -- ... )
 6019:   ... ;
 6020: IS deferred
 6021: @end example
 6022: 
 6023: @noindent
 6024: Gforth provides an alternative way of doing this, using two separate
 6025: words:
 6026: 
 6027: doc-noname
 6028: @cindex execution token of last defined word
 6029: doc-latestxt
 6030: 
 6031: @noindent
 6032: The previous example can be rewritten using @code{noname} and
 6033: @code{latestxt}:
 6034: 
 6035: @example
 6036: Defer deferred
 6037: noname : ( ... -- ... )
 6038:   ... ;
 6039: latestxt IS deferred
 6040: @end example
 6041: 
 6042: @noindent
 6043: @code{noname} works with any defining word, not just @code{:}.
 6044: 
 6045: @code{latestxt} also works when the last word was not defined as
 6046: @code{noname}.  It does not work for combined words, though.  It also has
 6047: the useful property that is is valid as soon as the header for a
 6048: definition has been built. Thus:
 6049: 
 6050: @example
 6051: latestxt . : foo [ latestxt . ] ; ' foo .
 6052: @end example
 6053: 
 6054: @noindent
 6055: prints 3 numbers; the last two are the same.
 6056: 
 6057: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6058: @subsection Supplying the name of a defined word
 6059: @cindex names for defined words
 6060: @cindex defining words, name given in a string
 6061: 
 6062: By default, a defining word takes the name for the defined word from the
 6063: input stream. Sometimes you want to supply the name from a string. You
 6064: can do this with:
 6065: 
 6066: doc-nextname
 6067: 
 6068: For example:
 6069: 
 6070: @example
 6071: s" foo" nextname create
 6072: @end example
 6073: 
 6074: @noindent
 6075: is equivalent to:
 6076: 
 6077: @example
 6078: create foo
 6079: @end example
 6080: 
 6081: @noindent
 6082: @code{nextname} works with any defining word.
 6083: 
 6084: 
 6085: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
 6086: @subsection User-defined Defining Words
 6087: @cindex user-defined defining words
 6088: @cindex defining words, user-defined
 6089: 
 6090: You can create a new defining word by wrapping defining-time code around
 6091: an existing defining word and putting the sequence in a colon
 6092: definition. 
 6093: 
 6094: @c anton: This example is very complex and leads in a quite different
 6095: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6096: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6097: @c subsection of Defining Words)
 6098: 
 6099: For example, suppose that you have a word @code{stats} that
 6100: gathers statistics about colon definitions given the @i{xt} of the
 6101: definition, and you want every colon definition in your application to
 6102: make a call to @code{stats}. You can define and use a new version of
 6103: @code{:} like this:
 6104: 
 6105: @example
 6106: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6107:   ... ;  \ other code
 6108: 
 6109: : my: : latestxt postpone literal ['] stats compile, ;
 6110: 
 6111: my: foo + - ;
 6112: @end example
 6113: 
 6114: When @code{foo} is defined using @code{my:} these steps occur:
 6115: 
 6116: @itemize @bullet
 6117: @item
 6118: @code{my:} is executed.
 6119: @item
 6120: The @code{:} within the definition (the one between @code{my:} and
 6121: @code{latestxt}) is executed, and does just what it always does; it parses
 6122: the input stream for a name, builds a dictionary header for the name
 6123: @code{foo} and switches @code{state} from interpret to compile.
 6124: @item
 6125: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6126: being defined -- @code{foo} -- onto the stack.
 6127: @item
 6128: The code that was produced by @code{postpone literal} is executed; this
 6129: causes the value on the stack to be compiled as a literal in the code
 6130: area of @code{foo}.
 6131: @item
 6132: The code @code{['] stats} compiles a literal into the definition of
 6133: @code{my:}. When @code{compile,} is executed, that literal -- the
 6134: execution token for @code{stats} -- is layed down in the code area of
 6135: @code{foo} , following the literal@footnote{Strictly speaking, the
 6136: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6137: in the code area is implementation-dependent. A threaded implementation
 6138: might spit out the execution token directly whilst another
 6139: implementation might spit out a native code sequence.}.
 6140: @item
 6141: At this point, the execution of @code{my:} is complete, and control
 6142: returns to the text interpreter. The text interpreter is in compile
 6143: state, so subsequent text @code{+ -} is compiled into the definition of
 6144: @code{foo} and the @code{;} terminates the definition as always.
 6145: @end itemize
 6146: 
 6147: You can use @code{see} to decompile a word that was defined using
 6148: @code{my:} and see how it is different from a normal @code{:}
 6149: definition. For example:
 6150: 
 6151: @example
 6152: : bar + - ;  \ like foo but using : rather than my:
 6153: see bar
 6154: : bar
 6155:   + - ;
 6156: see foo
 6157: : foo
 6158:   107645672 stats + - ;
 6159: 
 6160: \ use ' stats . to show that 107645672 is the xt for stats
 6161: @end example
 6162: 
 6163: You can use techniques like this to make new defining words in terms of
 6164: @i{any} existing defining word.
 6165: 
 6166: 
 6167: @cindex defining defining words
 6168: @cindex @code{CREATE} ... @code{DOES>}
 6169: If you want the words defined with your defining words to behave
 6170: differently from words defined with standard defining words, you can
 6171: write your defining word like this:
 6172: 
 6173: @example
 6174: : def-word ( "name" -- )
 6175:     CREATE @i{code1}
 6176: DOES> ( ... -- ... )
 6177:     @i{code2} ;
 6178: 
 6179: def-word name
 6180: @end example
 6181: 
 6182: @cindex child words
 6183: This fragment defines a @dfn{defining word} @code{def-word} and then
 6184: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6185: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6186: is not executed at this time. The word @code{name} is sometimes called a
 6187: @dfn{child} of @code{def-word}.
 6188: 
 6189: When you execute @code{name}, the address of the body of @code{name} is
 6190: put on the data stack and @i{code2} is executed (the address of the body
 6191: of @code{name} is the address @code{HERE} returns immediately after the
 6192: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6193: default).
 6194: 
 6195: @c anton:
 6196: @c www.dictionary.com says:
 6197: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6198: @c several generations of absence, usually caused by the chance
 6199: @c recombination of genes.  2.An individual or a part that exhibits
 6200: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6201: @c of previous behavior after a period of absence.
 6202: @c
 6203: @c Doesn't seem to fit.
 6204: 
 6205: @c @cindex atavism in child words
 6206: You can use @code{def-word} to define a set of child words that behave
 6207: similarly; they all have a common run-time behaviour determined by
 6208: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6209: body of the child word. The structure of the data is common to all
 6210: children of @code{def-word}, but the data values are specific -- and
 6211: private -- to each child word. When a child word is executed, the
 6212: address of its private data area is passed as a parameter on TOS to be
 6213: used and manipulated@footnote{It is legitimate both to read and write to
 6214: this data area.} by @i{code2}.
 6215: 
 6216: The two fragments of code that make up the defining words act (are
 6217: executed) at two completely separate times:
 6218: 
 6219: @itemize @bullet
 6220: @item
 6221: At @i{define time}, the defining word executes @i{code1} to generate a
 6222: child word
 6223: @item
 6224: At @i{child execution time}, when a child word is invoked, @i{code2}
 6225: is executed, using parameters (data) that are private and specific to
 6226: the child word.
 6227: @end itemize
 6228: 
 6229: Another way of understanding the behaviour of @code{def-word} and
 6230: @code{name} is to say that, if you make the following definitions:
 6231: @example
 6232: : def-word1 ( "name" -- )
 6233:     CREATE @i{code1} ;
 6234: 
 6235: : action1 ( ... -- ... )
 6236:     @i{code2} ;
 6237: 
 6238: def-word1 name1
 6239: @end example
 6240: 
 6241: @noindent
 6242: Then using @code{name1 action1} is equivalent to using @code{name}.
 6243: 
 6244: The classic example is that you can define @code{CONSTANT} in this way:
 6245: 
 6246: @example
 6247: : CONSTANT ( w "name" -- )
 6248:     CREATE ,
 6249: DOES> ( -- w )
 6250:     @@ ;
 6251: @end example
 6252: 
 6253: @comment There is a beautiful description of how this works and what
 6254: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6255: @comment commentary on the Counting Fruits problem.
 6256: 
 6257: When you create a constant with @code{5 CONSTANT five}, a set of
 6258: define-time actions take place; first a new word @code{five} is created,
 6259: then the value 5 is laid down in the body of @code{five} with
 6260: @code{,}. When @code{five} is executed, the address of the body is put on
 6261: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6262: no code of its own; it simply contains a data field and a pointer to the
 6263: code that follows @code{DOES>} in its defining word. That makes words
 6264: created in this way very compact.
 6265: 
 6266: The final example in this section is intended to remind you that space
 6267: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6268: both read and written by a Standard program@footnote{Exercise: use this
 6269: example as a starting point for your own implementation of @code{Value}
 6270: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6271: @code{[']}.}:
 6272: 
 6273: @example
 6274: : foo ( "name" -- )
 6275:     CREATE -1 ,
 6276: DOES> ( -- )
 6277:     @@ . ;
 6278: 
 6279: foo first-word
 6280: foo second-word
 6281: 
 6282: 123 ' first-word >BODY !
 6283: @end example
 6284: 
 6285: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6286: have executed it to get the address of its data field. However, since it
 6287: was defined to have @code{DOES>} actions, its execution semantics are to
 6288: perform those @code{DOES>} actions. To get the address of its data field
 6289: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6290: translate the xt into the address of the data field.  When you execute
 6291: @code{first-word}, it will display @code{123}. When you execute
 6292: @code{second-word} it will display @code{-1}.
 6293: 
 6294: @cindex stack effect of @code{DOES>}-parts
 6295: @cindex @code{DOES>}-parts, stack effect
 6296: In the examples above the stack comment after the @code{DOES>} specifies
 6297: the stack effect of the defined words, not the stack effect of the
 6298: following code (the following code expects the address of the body on
 6299: the top of stack, which is not reflected in the stack comment). This is
 6300: the convention that I use and recommend (it clashes a bit with using
 6301: locals declarations for stack effect specification, though).
 6302: 
 6303: @menu
 6304: * CREATE..DOES> applications::  
 6305: * CREATE..DOES> details::       
 6306: * Advanced does> usage example::  
 6307: * @code{Const-does>}::          
 6308: @end menu
 6309: 
 6310: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6311: @subsubsection Applications of @code{CREATE..DOES>}
 6312: @cindex @code{CREATE} ... @code{DOES>}, applications
 6313: 
 6314: You may wonder how to use this feature. Here are some usage patterns:
 6315: 
 6316: @cindex factoring similar colon definitions
 6317: When you see a sequence of code occurring several times, and you can
 6318: identify a meaning, you will factor it out as a colon definition. When
 6319: you see similar colon definitions, you can factor them using
 6320: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6321: that look very similar:
 6322: @example
 6323: : ori, ( reg-target reg-source n -- )
 6324:     0 asm-reg-reg-imm ;
 6325: : andi, ( reg-target reg-source n -- )
 6326:     1 asm-reg-reg-imm ;
 6327: @end example
 6328: 
 6329: @noindent
 6330: This could be factored with:
 6331: @example
 6332: : reg-reg-imm ( op-code -- )
 6333:     CREATE ,
 6334: DOES> ( reg-target reg-source n -- )
 6335:     @@ asm-reg-reg-imm ;
 6336: 
 6337: 0 reg-reg-imm ori,
 6338: 1 reg-reg-imm andi,
 6339: @end example
 6340: 
 6341: @cindex currying
 6342: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6343: supply a part of the parameters for a word (known as @dfn{currying} in
 6344: the functional language community). E.g., @code{+} needs two
 6345: parameters. Creating versions of @code{+} with one parameter fixed can
 6346: be done like this:
 6347: 
 6348: @example
 6349: : curry+ ( n1 "name" -- )
 6350:     CREATE ,
 6351: DOES> ( n2 -- n1+n2 )
 6352:     @@ + ;
 6353: 
 6354:  3 curry+ 3+
 6355: -2 curry+ 2-
 6356: @end example
 6357: 
 6358: 
 6359: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6360: @subsubsection The gory details of @code{CREATE..DOES>}
 6361: @cindex @code{CREATE} ... @code{DOES>}, details
 6362: 
 6363: doc-does>
 6364: 
 6365: @cindex @code{DOES>} in a separate definition
 6366: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6367: same definition; you can put the @code{DOES>}-part in a separate
 6368: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6369: @example
 6370: : does1 
 6371: DOES> ( ... -- ... )
 6372:     ... ;
 6373: 
 6374: : does2
 6375: DOES> ( ... -- ... )
 6376:     ... ;
 6377: 
 6378: : def-word ( ... -- ... )
 6379:     create ...
 6380:     IF
 6381:        does1
 6382:     ELSE
 6383:        does2
 6384:     ENDIF ;
 6385: @end example
 6386: 
 6387: In this example, the selection of whether to use @code{does1} or
 6388: @code{does2} is made at definition-time; at the time that the child word is
 6389: @code{CREATE}d.
 6390: 
 6391: @cindex @code{DOES>} in interpretation state
 6392: In a standard program you can apply a @code{DOES>}-part only if the last
 6393: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6394: will override the behaviour of the last word defined in any case. In a
 6395: standard program, you can use @code{DOES>} only in a colon
 6396: definition. In Gforth, you can also use it in interpretation state, in a
 6397: kind of one-shot mode; for example:
 6398: @example
 6399: CREATE name ( ... -- ... )
 6400:   @i{initialization}
 6401: DOES>
 6402:   @i{code} ;
 6403: @end example
 6404: 
 6405: @noindent
 6406: is equivalent to the standard:
 6407: @example
 6408: :noname
 6409: DOES>
 6410:     @i{code} ;
 6411: CREATE name EXECUTE ( ... -- ... )
 6412:     @i{initialization}
 6413: @end example
 6414: 
 6415: doc->body
 6416: 
 6417: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
 6418: @subsubsection Advanced does> usage example
 6419: 
 6420: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6421: for disassembling instructions, that follow a very repetetive scheme:
 6422: 
 6423: @example
 6424: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6425: @var{entry-num} cells @var{table} + !
 6426: @end example
 6427: 
 6428: Of course, this inspires the idea to factor out the commonalities to
 6429: allow a definition like
 6430: 
 6431: @example
 6432: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6433: @end example
 6434: 
 6435: The parameters @var{disasm-operands} and @var{table} are usually
 6436: correlated.  Moreover, before I wrote the disassembler, there already
 6437: existed code that defines instructions like this:
 6438: 
 6439: @example
 6440: @var{entry-num} @var{inst-format} @var{inst-name}
 6441: @end example
 6442: 
 6443: This code comes from the assembler and resides in
 6444: @file{arch/mips/insts.fs}.
 6445: 
 6446: So I had to define the @var{inst-format} words that performed the scheme
 6447: above when executed.  At first I chose to use run-time code-generation:
 6448: 
 6449: @example
 6450: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6451:   :noname Postpone @var{disasm-operands}
 6452:   name Postpone sliteral Postpone type Postpone ;
 6453:   swap cells @var{table} + ! ;
 6454: @end example
 6455: 
 6456: Note that this supplies the other two parameters of the scheme above.
 6457: 
 6458: An alternative would have been to write this using
 6459: @code{create}/@code{does>}:
 6460: 
 6461: @example
 6462: : @var{inst-format} ( entry-num "name" -- )
 6463:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6464:   noname create , ( entry-num )
 6465:   latestxt swap cells @var{table} + !
 6466: does> ( addr w -- )
 6467:   \ disassemble instruction w at addr
 6468:   @@ >r 
 6469:   @var{disasm-operands}
 6470:   r> count type ;
 6471: @end example
 6472: 
 6473: Somehow the first solution is simpler, mainly because it's simpler to
 6474: shift a string from definition-time to use-time with @code{sliteral}
 6475: than with @code{string,} and friends.
 6476: 
 6477: I wrote a lot of words following this scheme and soon thought about
 6478: factoring out the commonalities among them.  Note that this uses a
 6479: two-level defining word, i.e., a word that defines ordinary defining
 6480: words.
 6481: 
 6482: This time a solution involving @code{postpone} and friends seemed more
 6483: difficult (try it as an exercise), so I decided to use a
 6484: @code{create}/@code{does>} word; since I was already at it, I also used
 6485: @code{create}/@code{does>} for the lower level (try using
 6486: @code{postpone} etc. as an exercise), resulting in the following
 6487: definition:
 6488: 
 6489: @example
 6490: : define-format ( disasm-xt table-xt -- )
 6491:     \ define an instruction format that uses disasm-xt for
 6492:     \ disassembling and enters the defined instructions into table
 6493:     \ table-xt
 6494:     create 2,
 6495: does> ( u "inst" -- )
 6496:     \ defines an anonymous word for disassembling instruction inst,
 6497:     \ and enters it as u-th entry into table-xt
 6498:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6499:     noname create 2,      \ define anonymous word
 6500:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6501: does> ( addr w -- )
 6502:     \ disassemble instruction w at addr
 6503:     2@@ >r ( addr w disasm-xt R: c-addr )
 6504:     execute ( R: c-addr ) \ disassemble operands
 6505:     r> count type ; \ print name 
 6506: @end example
 6507: 
 6508: Note that the tables here (in contrast to above) do the @code{cells +}
 6509: by themselves (that's why you have to pass an xt).  This word is used in
 6510: the following way:
 6511: 
 6512: @example
 6513: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6514: @end example
 6515: 
 6516: As shown above, the defined instruction format is then used like this:
 6517: 
 6518: @example
 6519: @var{entry-num} @var{inst-format} @var{inst-name}
 6520: @end example
 6521: 
 6522: In terms of currying, this kind of two-level defining word provides the
 6523: parameters in three stages: first @var{disasm-operands} and @var{table},
 6524: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6525: the instruction to be disassembled.  
 6526: 
 6527: Of course this did not quite fit all the instruction format names used
 6528: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6529: the parameters into the right form.
 6530: 
 6531: If you have trouble following this section, don't worry.  First, this is
 6532: involved and takes time (and probably some playing around) to
 6533: understand; second, this is the first two-level
 6534: @code{create}/@code{does>} word I have written in seventeen years of
 6535: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6536: have elected to use just a one-level defining word (with some repeating
 6537: of parameters when using the defining word). So it is not necessary to
 6538: understand this, but it may improve your understanding of Forth.
 6539: 
 6540: 
 6541: @node @code{Const-does>},  , Advanced does> usage example, User-defined Defining Words
 6542: @subsubsection @code{Const-does>}
 6543: 
 6544: A frequent use of @code{create}...@code{does>} is for transferring some
 6545: values from definition-time to run-time.  Gforth supports this use with
 6546: 
 6547: doc-const-does>
 6548: 
 6549: A typical use of this word is:
 6550: 
 6551: @example
 6552: : curry+ ( n1 "name" -- )
 6553: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6554:     + ;
 6555: 
 6556: 3 curry+ 3+
 6557: @end example
 6558: 
 6559: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6560: definition to run-time.
 6561: 
 6562: The advantages of using @code{const-does>} are:
 6563: 
 6564: @itemize
 6565: 
 6566: @item
 6567: You don't have to deal with storing and retrieving the values, i.e.,
 6568: your program becomes more writable and readable.
 6569: 
 6570: @item
 6571: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6572: be optimized away (because you could change the data using
 6573: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6574: 
 6575: @end itemize
 6576: 
 6577: An ANS Forth implementation of @code{const-does>} is available in
 6578: @file{compat/const-does.fs}.
 6579: 
 6580: 
 6581: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 6582: @subsection Deferred words
 6583: @cindex deferred words
 6584: 
 6585: The defining word @code{Defer} allows you to define a word by name
 6586: without defining its behaviour; the definition of its behaviour is
 6587: deferred. Here are two situation where this can be useful:
 6588: 
 6589: @itemize @bullet
 6590: @item
 6591: Where you want to allow the behaviour of a word to be altered later, and
 6592: for all precompiled references to the word to change when its behaviour
 6593: is changed.
 6594: @item
 6595: For mutual recursion; @xref{Calls and returns}.
 6596: @end itemize
 6597: 
 6598: In the following example, @code{foo} always invokes the version of
 6599: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6600: always invokes the version that prints ``@code{Hello}''. There is no way
 6601: of getting @code{foo} to use the later version without re-ordering the
 6602: source code and recompiling it.
 6603: 
 6604: @example
 6605: : greet ." Good morning" ;
 6606: : foo ... greet ... ;
 6607: : greet ." Hello" ;
 6608: : bar ... greet ... ;
 6609: @end example
 6610: 
 6611: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6612: word. The behaviour of a @code{Defer}red word can be defined and
 6613: redefined at any time by using @code{IS} to associate the xt of a
 6614: previously-defined word with it. The previous example becomes:
 6615: 
 6616: @example
 6617: Defer greet ( -- )
 6618: : foo ... greet ... ;
 6619: : bar ... greet ... ;
 6620: : greet1 ( -- ) ." Good morning" ;
 6621: : greet2 ( -- ) ." Hello" ;
 6622: ' greet2 IS greet  \ make greet behave like greet2
 6623: @end example
 6624: 
 6625: @progstyle
 6626: You should write a stack comment for every deferred word, and put only
 6627: XTs into deferred words that conform to this stack effect.  Otherwise
 6628: it's too difficult to use the deferred word.
 6629: 
 6630: A deferred word can be used to improve the statistics-gathering example
 6631: from @ref{User-defined Defining Words}; rather than edit the
 6632: application's source code to change every @code{:} to a @code{my:}, do
 6633: this:
 6634: 
 6635: @example
 6636: : real: : ;     \ retain access to the original
 6637: defer :         \ redefine as a deferred word
 6638: ' my: IS :      \ use special version of :
 6639: \
 6640: \ load application here
 6641: \
 6642: ' real: IS :    \ go back to the original
 6643: @end example
 6644: 
 6645: 
 6646: One thing to note is that @code{IS} has special compilation semantics,
 6647: such that it parses the name at compile time (like @code{TO}):
 6648: 
 6649: @example
 6650: : set-greet ( xt -- )
 6651:   IS greet ;
 6652: 
 6653: ' greet1 set-greet
 6654: @end example
 6655: 
 6656: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6657: 
 6658: A deferred word can only inherit execution semantics from the xt
 6659: (because that is all that an xt can represent -- for more discussion of
 6660: this @pxref{Tokens for Words}); by default it will have default
 6661: interpretation and compilation semantics deriving from this execution
 6662: semantics.  However, you can change the interpretation and compilation
 6663: semantics of the deferred word in the usual ways:
 6664: 
 6665: @example
 6666: : bar .... ; immediate
 6667: Defer fred immediate
 6668: Defer jim
 6669: 
 6670: ' bar IS jim  \ jim has default semantics
 6671: ' bar IS fred \ fred is immediate
 6672: @end example
 6673: 
 6674: doc-defer
 6675: doc-defer!
 6676: doc-is
 6677: doc-defer@
 6678: doc-action-of
 6679: @comment TODO document these: what's defers [is]
 6680: doc-defers
 6681: 
 6682: @c Use @code{words-deferred} to see a list of deferred words.
 6683: 
 6684: Definitions of these words (except @code{defers}) in ANS Forth are
 6685: provided in @file{compat/defer.fs}.
 6686: 
 6687: 
 6688: @node Aliases,  , Deferred words, Defining Words
 6689: @subsection Aliases
 6690: @cindex aliases
 6691: 
 6692: The defining word @code{Alias} allows you to define a word by name that
 6693: has the same behaviour as some other word. Here are two situation where
 6694: this can be useful:
 6695: 
 6696: @itemize @bullet
 6697: @item
 6698: When you want access to a word's definition from a different word list
 6699: (for an example of this, see the definition of the @code{Root} word list
 6700: in the Gforth source).
 6701: @item
 6702: When you want to create a synonym; a definition that can be known by
 6703: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6704: aliases).
 6705: @end itemize
 6706: 
 6707: Like deferred words, an alias has default compilation and interpretation
 6708: semantics at the beginning (not the modifications of the other word),
 6709: but you can change them in the usual ways (@code{immediate},
 6710: @code{compile-only}). For example:
 6711: 
 6712: @example
 6713: : foo ... ; immediate
 6714: 
 6715: ' foo Alias bar \ bar is not an immediate word
 6716: ' foo Alias fooby immediate \ fooby is an immediate word
 6717: @end example
 6718: 
 6719: Words that are aliases have the same xt, different headers in the
 6720: dictionary, and consequently different name tokens (@pxref{Tokens for
 6721: Words}) and possibly different immediate flags.  An alias can only have
 6722: default or immediate compilation semantics; you can define aliases for
 6723: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6724: 
 6725: doc-alias
 6726: 
 6727: 
 6728: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6729: @section Interpretation and Compilation Semantics
 6730: @cindex semantics, interpretation and compilation
 6731: 
 6732: @c !! state and ' are used without explanation
 6733: @c example for immediate/compile-only? or is the tutorial enough
 6734: 
 6735: @cindex interpretation semantics
 6736: The @dfn{interpretation semantics} of a (named) word are what the text
 6737: interpreter does when it encounters the word in interpret state. It also
 6738: appears in some other contexts, e.g., the execution token returned by
 6739: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6740: (in other words, @code{' @i{word} execute} is equivalent to
 6741: interpret-state text interpretation of @code{@i{word}}).
 6742: 
 6743: @cindex compilation semantics
 6744: The @dfn{compilation semantics} of a (named) word are what the text
 6745: interpreter does when it encounters the word in compile state. It also
 6746: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6747: compiles@footnote{In standard terminology, ``appends to the current
 6748: definition''.} the compilation semantics of @i{word}.
 6749: 
 6750: @cindex execution semantics
 6751: The standard also talks about @dfn{execution semantics}. They are used
 6752: only for defining the interpretation and compilation semantics of many
 6753: words. By default, the interpretation semantics of a word are to
 6754: @code{execute} its execution semantics, and the compilation semantics of
 6755: a word are to @code{compile,} its execution semantics.@footnote{In
 6756: standard terminology: The default interpretation semantics are its
 6757: execution semantics; the default compilation semantics are to append its
 6758: execution semantics to the execution semantics of the current
 6759: definition.}
 6760: 
 6761: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6762: the text interpreter, ticked, or @code{postpone}d, so they have no
 6763: interpretation or compilation semantics.  Their behaviour is represented
 6764: by their XT (@pxref{Tokens for Words}), and we call it execution
 6765: semantics, too.
 6766: 
 6767: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6768: 
 6769: @cindex immediate words
 6770: @cindex compile-only words
 6771: You can change the semantics of the most-recently defined word:
 6772: 
 6773: 
 6774: doc-immediate
 6775: doc-compile-only
 6776: doc-restrict
 6777: 
 6778: By convention, words with non-default compilation semantics (e.g.,
 6779: immediate words) often have names surrounded with brackets (e.g.,
 6780: @code{[']}, @pxref{Execution token}).
 6781: 
 6782: Note that ticking (@code{'}) a compile-only word gives an error
 6783: (``Interpreting a compile-only word'').
 6784: 
 6785: @menu
 6786: * Combined words::              
 6787: @end menu
 6788: 
 6789: 
 6790: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 6791: @subsection Combined Words
 6792: @cindex combined words
 6793: 
 6794: Gforth allows you to define @dfn{combined words} -- words that have an
 6795: arbitrary combination of interpretation and compilation semantics.
 6796: 
 6797: doc-interpret/compile:
 6798: 
 6799: This feature was introduced for implementing @code{TO} and @code{S"}. I
 6800: recommend that you do not define such words, as cute as they may be:
 6801: they make it hard to get at both parts of the word in some contexts.
 6802: E.g., assume you want to get an execution token for the compilation
 6803: part. Instead, define two words, one that embodies the interpretation
 6804: part, and one that embodies the compilation part.  Once you have done
 6805: that, you can define a combined word with @code{interpret/compile:} for
 6806: the convenience of your users.
 6807: 
 6808: You might try to use this feature to provide an optimizing
 6809: implementation of the default compilation semantics of a word. For
 6810: example, by defining:
 6811: @example
 6812: :noname
 6813:    foo bar ;
 6814: :noname
 6815:    POSTPONE foo POSTPONE bar ;
 6816: interpret/compile: opti-foobar
 6817: @end example
 6818: 
 6819: @noindent
 6820: as an optimizing version of:
 6821: 
 6822: @example
 6823: : foobar
 6824:     foo bar ;
 6825: @end example
 6826: 
 6827: Unfortunately, this does not work correctly with @code{[compile]},
 6828: because @code{[compile]} assumes that the compilation semantics of all
 6829: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 6830: opti-foobar} would compile compilation semantics, whereas
 6831: @code{[compile] foobar} would compile interpretation semantics.
 6832: 
 6833: @cindex state-smart words (are a bad idea)
 6834: @anchor{state-smartness}
 6835: Some people try to use @dfn{state-smart} words to emulate the feature provided
 6836: by @code{interpret/compile:} (words are state-smart if they check
 6837: @code{STATE} during execution). E.g., they would try to code
 6838: @code{foobar} like this:
 6839: 
 6840: @example
 6841: : foobar
 6842:   STATE @@
 6843:   IF ( compilation state )
 6844:     POSTPONE foo POSTPONE bar
 6845:   ELSE
 6846:     foo bar
 6847:   ENDIF ; immediate
 6848: @end example
 6849: 
 6850: Although this works if @code{foobar} is only processed by the text
 6851: interpreter, it does not work in other contexts (like @code{'} or
 6852: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 6853: for a state-smart word, not for the interpretation semantics of the
 6854: original @code{foobar}; when you execute this execution token (directly
 6855: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 6856: state, the result will not be what you expected (i.e., it will not
 6857: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 6858: write them@footnote{For a more detailed discussion of this topic, see
 6859: M. Anton Ertl,
 6860: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 6861: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 6862: 
 6863: @cindex defining words with arbitrary semantics combinations
 6864: It is also possible to write defining words that define words with
 6865: arbitrary combinations of interpretation and compilation semantics. In
 6866: general, they look like this:
 6867: 
 6868: @example
 6869: : def-word
 6870:     create-interpret/compile
 6871:     @i{code1}
 6872: interpretation>
 6873:     @i{code2}
 6874: <interpretation
 6875: compilation>
 6876:     @i{code3}
 6877: <compilation ;
 6878: @end example
 6879: 
 6880: For a @i{word} defined with @code{def-word}, the interpretation
 6881: semantics are to push the address of the body of @i{word} and perform
 6882: @i{code2}, and the compilation semantics are to push the address of
 6883: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 6884: can also be defined like this (except that the defined constants don't
 6885: behave correctly when @code{[compile]}d):
 6886: 
 6887: @example
 6888: : constant ( n "name" -- )
 6889:     create-interpret/compile
 6890:     ,
 6891: interpretation> ( -- n )
 6892:     @@
 6893: <interpretation
 6894: compilation> ( compilation. -- ; run-time. -- n )
 6895:     @@ postpone literal
 6896: <compilation ;
 6897: @end example
 6898: 
 6899: 
 6900: doc-create-interpret/compile
 6901: doc-interpretation>
 6902: doc-<interpretation
 6903: doc-compilation>
 6904: doc-<compilation
 6905: 
 6906: 
 6907: Words defined with @code{interpret/compile:} and
 6908: @code{create-interpret/compile} have an extended header structure that
 6909: differs from other words; however, unless you try to access them with
 6910: plain address arithmetic, you should not notice this. Words for
 6911: accessing the header structure usually know how to deal with this; e.g.,
 6912: @code{'} @i{word} @code{>body} also gives you the body of a word created
 6913: with @code{create-interpret/compile}.
 6914: 
 6915: 
 6916: @c -------------------------------------------------------------
 6917: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 6918: @section Tokens for Words
 6919: @cindex tokens for words
 6920: 
 6921: This section describes the creation and use of tokens that represent
 6922: words.
 6923: 
 6924: @menu
 6925: * Execution token::             represents execution/interpretation semantics
 6926: * Compilation token::           represents compilation semantics
 6927: * Name token::                  represents named words
 6928: @end menu
 6929: 
 6930: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 6931: @subsection Execution token
 6932: 
 6933: @cindex xt
 6934: @cindex execution token
 6935: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 6936: You can use @code{execute} to invoke this behaviour.
 6937: 
 6938: @cindex tick (')
 6939: You can use @code{'} to get an execution token that represents the
 6940: interpretation semantics of a named word:
 6941: 
 6942: @example
 6943: 5 ' .   ( n xt ) 
 6944: execute ( )      \ execute the xt (i.e., ".")
 6945: @end example
 6946: 
 6947: doc-'
 6948: 
 6949: @code{'} parses at run-time; there is also a word @code{[']} that parses
 6950: when it is compiled, and compiles the resulting XT:
 6951: 
 6952: @example
 6953: : foo ['] . execute ;
 6954: 5 foo
 6955: : bar ' execute ; \ by contrast,
 6956: 5 bar .           \ ' parses "." when bar executes
 6957: @end example
 6958: 
 6959: doc-[']
 6960: 
 6961: If you want the execution token of @i{word}, write @code{['] @i{word}}
 6962: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 6963: @code{'} and @code{[']} behave somewhat unusually by complaining about
 6964: compile-only words (because these words have no interpretation
 6965: semantics).  You might get what you want by using @code{COMP' @i{word}
 6966: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 6967: token}).
 6968: 
 6969: Another way to get an XT is @code{:noname} or @code{latestxt}
 6970: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 6971: for the only behaviour the word has (the execution semantics).  For
 6972: named words, @code{latestxt} produces an XT for the same behaviour it
 6973: would produce if the word was defined anonymously.
 6974: 
 6975: @example
 6976: :noname ." hello" ;
 6977: execute
 6978: @end example
 6979: 
 6980: An XT occupies one cell and can be manipulated like any other cell.
 6981: 
 6982: @cindex code field address
 6983: @cindex CFA
 6984: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 6985: operations that produce or consume it).  For old hands: In Gforth, the
 6986: XT is implemented as a code field address (CFA).
 6987: 
 6988: doc-execute
 6989: doc-perform
 6990: 
 6991: @node Compilation token, Name token, Execution token, Tokens for Words
 6992: @subsection Compilation token
 6993: 
 6994: @cindex compilation token
 6995: @cindex CT (compilation token)
 6996: Gforth represents the compilation semantics of a named word by a
 6997: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 6998: @i{xt} is an execution token. The compilation semantics represented by
 6999: the compilation token can be performed with @code{execute}, which
 7000: consumes the whole compilation token, with an additional stack effect
 7001: determined by the represented compilation semantics.
 7002: 
 7003: At present, the @i{w} part of a compilation token is an execution token,
 7004: and the @i{xt} part represents either @code{execute} or
 7005: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7006: word. If the word has default compilation semantics, the @i{xt} will
 7007: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7008: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7009: knowledge, unless necessary; future versions of Gforth may introduce
 7010: unusual compilation tokens (e.g., a compilation token that represents
 7011: the compilation semantics of a literal).
 7012: 
 7013: You can perform the compilation semantics represented by the compilation
 7014: token with @code{execute}.  You can compile the compilation semantics
 7015: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7016: equivalent to @code{postpone @i{word}}.
 7017: 
 7018: doc-[comp']
 7019: doc-comp'
 7020: doc-postpone,
 7021: 
 7022: @node Name token,  , Compilation token, Tokens for Words
 7023: @subsection Name token
 7024: 
 7025: @cindex name token
 7026: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7027: token is an abstract data type that occurs as argument or result of the
 7028: words below.
 7029: 
 7030: @c !! put this elswhere?
 7031: @cindex name field address
 7032: @cindex NFA
 7033: The closest thing to the nt in older Forth systems is the name field
 7034: address (NFA), but there are significant differences: in older Forth
 7035: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7036: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7037: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7038: is a link field in the structure identified by the name token, but
 7039: searching usually uses a hash table external to these structures; the
 7040: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7041: implemented as the address of that count field.
 7042: 
 7043: doc-find-name
 7044: doc-latest
 7045: doc->name
 7046: doc-name>int
 7047: doc-name?int
 7048: doc-name>comp
 7049: doc-name>string
 7050: doc-id.
 7051: doc-.name
 7052: doc-.id
 7053: 
 7054: @c ----------------------------------------------------------
 7055: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7056: @section Compiling words
 7057: @cindex compiling words
 7058: @cindex macros
 7059: 
 7060: In contrast to most other languages, Forth has no strict boundary
 7061: between compilation and run-time.  E.g., you can run arbitrary code
 7062: between defining words (or for computing data used by defining words
 7063: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7064: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7065: running arbitrary code while compiling a colon definition (exception:
 7066: you must not allot dictionary space).
 7067: 
 7068: @menu
 7069: * Literals::                    Compiling data values
 7070: * Macros::                      Compiling words
 7071: @end menu
 7072: 
 7073: @node Literals, Macros, Compiling words, Compiling words
 7074: @subsection Literals
 7075: @cindex Literals
 7076: 
 7077: The simplest and most frequent example is to compute a literal during
 7078: compilation.  E.g., the following definition prints an array of strings,
 7079: one string per line:
 7080: 
 7081: @example
 7082: : .strings ( addr u -- ) \ gforth
 7083:     2* cells bounds U+DO
 7084: 	cr i 2@@ type
 7085:     2 cells +LOOP ;  
 7086: @end example
 7087: 
 7088: With a simple-minded compiler like Gforth's, this computes @code{2
 7089: cells} on every loop iteration.  You can compute this value once and for
 7090: all at compile time and compile it into the definition like this:
 7091: 
 7092: @example
 7093: : .strings ( addr u -- ) \ gforth
 7094:     2* cells bounds U+DO
 7095: 	cr i 2@@ type
 7096:     [ 2 cells ] literal +LOOP ;  
 7097: @end example
 7098: 
 7099: @code{[} switches the text interpreter to interpret state (you will get
 7100: an @code{ok} prompt if you type this example interactively and insert a
 7101: newline between @code{[} and @code{]}), so it performs the
 7102: interpretation semantics of @code{2 cells}; this computes a number.
 7103: @code{]} switches the text interpreter back into compile state.  It then
 7104: performs @code{Literal}'s compilation semantics, which are to compile
 7105: this number into the current word.  You can decompile the word with
 7106: @code{see .strings} to see the effect on the compiled code.
 7107: 
 7108: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7109: *} in this way.
 7110: 
 7111: doc-[
 7112: doc-]
 7113: doc-literal
 7114: doc-]L
 7115: 
 7116: There are also words for compiling other data types than single cells as
 7117: literals:
 7118: 
 7119: doc-2literal
 7120: doc-fliteral
 7121: doc-sliteral
 7122: 
 7123: @cindex colon-sys, passing data across @code{:}
 7124: @cindex @code{:}, passing data across
 7125: You might be tempted to pass data from outside a colon definition to the
 7126: inside on the data stack.  This does not work, because @code{:} puhes a
 7127: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7128: 
 7129: @example
 7130: 5 : foo literal ; \ error: "unstructured"
 7131: @end example
 7132: 
 7133: Instead, you have to pass the value in some other way, e.g., through a
 7134: variable:
 7135: 
 7136: @example
 7137: variable temp
 7138: 5 temp !
 7139: : foo [ temp @@ ] literal ;
 7140: @end example
 7141: 
 7142: 
 7143: @node Macros,  , Literals, Compiling words
 7144: @subsection Macros
 7145: @cindex Macros
 7146: @cindex compiling compilation semantics
 7147: 
 7148: @code{Literal} and friends compile data values into the current
 7149: definition.  You can also write words that compile other words into the
 7150: current definition.  E.g.,
 7151: 
 7152: @example
 7153: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7154:   POSTPONE + ;
 7155: 
 7156: : foo ( n1 n2 -- n )
 7157:   [ compile-+ ] ;
 7158: 1 2 foo .
 7159: @end example
 7160: 
 7161: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7162: What happens in this example?  @code{Postpone} compiles the compilation
 7163: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7164: executes @code{compile-+} and thus the compilation semantics of +, which
 7165: compile (the execution semantics of) @code{+} into
 7166: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7167: should only be executed in compile state, so this example is not
 7168: guaranteed to work on all standard systems, but on any decent system it
 7169: will work.}
 7170: 
 7171: doc-postpone
 7172: doc-[compile]
 7173: 
 7174: Compiling words like @code{compile-+} are usually immediate (or similar)
 7175: so you do not have to switch to interpret state to execute them;
 7176: mopifying the last example accordingly produces:
 7177: 
 7178: @example
 7179: : [compile-+] ( compilation: --; interpretation: -- )
 7180:   \ compiled code: ( n1 n2 -- n )
 7181:   POSTPONE + ; immediate
 7182: 
 7183: : foo ( n1 n2 -- n )
 7184:   [compile-+] ;
 7185: 1 2 foo .
 7186: @end example
 7187: 
 7188: Immediate compiling words are similar to macros in other languages (in
 7189: particular, Lisp).  The important differences to macros in, e.g., C are:
 7190: 
 7191: @itemize @bullet
 7192: 
 7193: @item
 7194: You use the same language for defining and processing macros, not a
 7195: separate preprocessing language and processor.
 7196: 
 7197: @item
 7198: Consequently, the full power of Forth is available in macro definitions.
 7199: E.g., you can perform arbitrarily complex computations, or generate
 7200: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7201: Tutorial}).  This power is very useful when writing a parser generators
 7202: or other code-generating software.
 7203: 
 7204: @item
 7205: Macros defined using @code{postpone} etc. deal with the language at a
 7206: higher level than strings; name binding happens at macro definition
 7207: time, so you can avoid the pitfalls of name collisions that can happen
 7208: in C macros.  Of course, Forth is a liberal language and also allows to
 7209: shoot yourself in the foot with text-interpreted macros like
 7210: 
 7211: @example
 7212: : [compile-+] s" +" evaluate ; immediate
 7213: @end example
 7214: 
 7215: Apart from binding the name at macro use time, using @code{evaluate}
 7216: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7217: @end itemize
 7218: 
 7219: You may want the macro to compile a number into a word.  The word to do
 7220: it is @code{literal}, but you have to @code{postpone} it, so its
 7221: compilation semantics take effect when the macro is executed, not when
 7222: it is compiled:
 7223: 
 7224: @example
 7225: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7226:   5 POSTPONE literal ; immediate
 7227: 
 7228: : foo [compile-5] ;
 7229: foo .
 7230: @end example
 7231: 
 7232: You may want to pass parameters to a macro, that the macro should
 7233: compile into the current definition.  If the parameter is a number, then
 7234: you can use @code{postpone literal} (similar for other values).
 7235: 
 7236: If you want to pass a word that is to be compiled, the usual way is to
 7237: pass an execution token and @code{compile,} it:
 7238: 
 7239: @example
 7240: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7241:   dup compile, compile, ;
 7242: 
 7243: : 2+ ( n1 -- n2 )
 7244:   [ ' 1+ twice1 ] ;
 7245: @end example
 7246: 
 7247: doc-compile,
 7248: 
 7249: An alternative available in Gforth, that allows you to pass compile-only
 7250: words as parameters is to use the compilation token (@pxref{Compilation
 7251: token}).  The same example in this technique:
 7252: 
 7253: @example
 7254: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7255:   2dup 2>r execute 2r> execute ;
 7256: 
 7257: : 2+ ( n1 -- n2 )
 7258:   [ comp' 1+ twice ] ;
 7259: @end example
 7260: 
 7261: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7262: works even if the executed compilation semantics has an effect on the
 7263: data stack.
 7264: 
 7265: You can also define complete definitions with these words; this provides
 7266: an alternative to using @code{does>} (@pxref{User-defined Defining
 7267: Words}).  E.g., instead of
 7268: 
 7269: @example
 7270: : curry+ ( n1 "name" -- )
 7271:     CREATE ,
 7272: DOES> ( n2 -- n1+n2 )
 7273:     @@ + ;
 7274: @end example
 7275: 
 7276: you could define
 7277: 
 7278: @example
 7279: : curry+ ( n1 "name" -- )
 7280:   \ name execution: ( n2 -- n1+n2 )
 7281:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7282: 
 7283: -3 curry+ 3-
 7284: see 3-
 7285: @end example
 7286: 
 7287: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7288: colon-sys on the data stack that makes everything below it unaccessible.
 7289: 
 7290: This way of writing defining words is sometimes more, sometimes less
 7291: convenient than using @code{does>} (@pxref{Advanced does> usage
 7292: example}).  One advantage of this method is that it can be optimized
 7293: better, because the compiler knows that the value compiled with
 7294: @code{literal} is fixed, whereas the data associated with a
 7295: @code{create}d word can be changed.
 7296: 
 7297: @c ----------------------------------------------------------
 7298: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7299: @section  The Text Interpreter
 7300: @cindex interpreter - outer
 7301: @cindex text interpreter
 7302: @cindex outer interpreter
 7303: 
 7304: @c Should we really describe all these ugly details?  IMO the text
 7305: @c interpreter should be much cleaner, but that may not be possible within
 7306: @c ANS Forth. - anton
 7307: @c nac-> I wanted to explain how it works to show how you can exploit
 7308: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7309: @c some of these gory details was very helpful to me. None of the textbooks
 7310: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7311: @c seems to positively avoid going into too much detail for some of
 7312: @c the internals.
 7313: 
 7314: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7315: @c it is; for the ugly details, I would prefer another place.  I wonder
 7316: @c whether we should have a chapter before "Words" that describes some
 7317: @c basic concepts referred to in words, and a chapter after "Words" that
 7318: @c describes implementation details.
 7319: 
 7320: The text interpreter@footnote{This is an expanded version of the
 7321: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7322: that processes input from the current input device. It is also called
 7323: the outer interpreter, in contrast to the inner interpreter
 7324: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7325: implementations.
 7326: 
 7327: @cindex interpret state
 7328: @cindex compile state
 7329: The text interpreter operates in one of two states: @dfn{interpret
 7330: state} and @dfn{compile state}. The current state is defined by the
 7331: aptly-named variable @code{state}.
 7332: 
 7333: This section starts by describing how the text interpreter behaves when
 7334: it is in interpret state, processing input from the user input device --
 7335: the keyboard. This is the mode that a Forth system is in after it starts
 7336: up.
 7337: 
 7338: @cindex input buffer
 7339: @cindex terminal input buffer
 7340: The text interpreter works from an area of memory called the @dfn{input
 7341: buffer}@footnote{When the text interpreter is processing input from the
 7342: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7343: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7344: @code{#TIB}.}, which stores your keyboard input when you press the
 7345: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7346: leading spaces (called @dfn{delimiters}) then parses a string (a
 7347: sequence of non-space characters) until it reaches either a space
 7348: character or the end of the buffer. Having parsed a string, it makes two
 7349: attempts to process it:
 7350: 
 7351: @cindex dictionary
 7352: @itemize @bullet
 7353: @item
 7354: It looks for the string in a @dfn{dictionary} of definitions. If the
 7355: string is found, the string names a @dfn{definition} (also known as a
 7356: @dfn{word}) and the dictionary search returns information that allows
 7357: the text interpreter to perform the word's @dfn{interpretation
 7358: semantics}. In most cases, this simply means that the word will be
 7359: executed.
 7360: @item
 7361: If the string is not found in the dictionary, the text interpreter
 7362: attempts to treat it as a number, using the rules described in
 7363: @ref{Number Conversion}. If the string represents a legal number in the
 7364: current radix, the number is pushed onto a parameter stack (the data
 7365: stack for integers, the floating-point stack for floating-point
 7366: numbers).
 7367: @end itemize
 7368: 
 7369: If both attempts fail, or if the word is found in the dictionary but has
 7370: no interpretation semantics@footnote{This happens if the word was
 7371: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7372: remainder of the input buffer, issues an error message and waits for
 7373: more input. If one of the attempts succeeds, the text interpreter
 7374: repeats the parsing process until the whole of the input buffer has been
 7375: processed, at which point it prints the status message ``@code{ ok}''
 7376: and waits for more input.
 7377: 
 7378: @c anton: this should be in the input stream subsection (or below it)
 7379: 
 7380: @cindex parse area
 7381: The text interpreter keeps track of its position in the input buffer by
 7382: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7383: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7384: of the input buffer. The region from offset @code{>IN @@} to the end of
 7385: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7386: the text interpreter processes the contents of the input buffer by
 7387: parsing strings from the parse area until the parse area is empty.}.
 7388: This example shows how @code{>IN} changes as the text interpreter parses
 7389: the input buffer:
 7390: 
 7391: @example
 7392: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7393:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7394: 
 7395: 1 2 3 remaining + remaining . 
 7396: 
 7397: : foo 1 2 3 remaining SWAP remaining ;
 7398: @end example
 7399: 
 7400: @noindent
 7401: The result is:
 7402: 
 7403: @example
 7404: ->+ remaining .<-
 7405: ->.<-5  ok
 7406: 
 7407: ->SWAP remaining ;-<
 7408: ->;<-  ok
 7409: @end example
 7410: 
 7411: @cindex parsing words
 7412: The value of @code{>IN} can also be modified by a word in the input
 7413: buffer that is executed by the text interpreter.  This means that a word
 7414: can ``trick'' the text interpreter into either skipping a section of the
 7415: input buffer@footnote{This is how parsing words work.} or into parsing a
 7416: section twice. For example:
 7417: 
 7418: @example
 7419: : lat ." <<foo>>" ;
 7420: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7421: @end example
 7422: 
 7423: @noindent
 7424: When @code{flat} is executed, this output is produced@footnote{Exercise
 7425: for the reader: what would happen if the @code{3} were replaced with
 7426: @code{4}?}:
 7427: 
 7428: @example
 7429: <<bar>><<foo>>
 7430: @end example
 7431: 
 7432: This technique can be used to work around some of the interoperability
 7433: problems of parsing words.  Of course, it's better to avoid parsing
 7434: words where possible.
 7435: 
 7436: @noindent
 7437: Two important notes about the behaviour of the text interpreter:
 7438: 
 7439: @itemize @bullet
 7440: @item
 7441: It processes each input string to completion before parsing additional
 7442: characters from the input buffer.
 7443: @item
 7444: It treats the input buffer as a read-only region (and so must your code).
 7445: @end itemize
 7446: 
 7447: @noindent
 7448: When the text interpreter is in compile state, its behaviour changes in
 7449: these ways:
 7450: 
 7451: @itemize @bullet
 7452: @item
 7453: If a parsed string is found in the dictionary, the text interpreter will
 7454: perform the word's @dfn{compilation semantics}. In most cases, this
 7455: simply means that the execution semantics of the word will be appended
 7456: to the current definition.
 7457: @item
 7458: When a number is encountered, it is compiled into the current definition
 7459: (as a literal) rather than being pushed onto a parameter stack.
 7460: @item
 7461: If an error occurs, @code{state} is modified to put the text interpreter
 7462: back into interpret state.
 7463: @item
 7464: Each time a line is entered from the keyboard, Gforth prints
 7465: ``@code{ compiled}'' rather than `` @code{ok}''.
 7466: @end itemize
 7467: 
 7468: @cindex text interpreter - input sources
 7469: When the text interpreter is using an input device other than the
 7470: keyboard, its behaviour changes in these ways:
 7471: 
 7472: @itemize @bullet
 7473: @item
 7474: When the parse area is empty, the text interpreter attempts to refill
 7475: the input buffer from the input source. When the input source is
 7476: exhausted, the input source is set back to the previous input source.
 7477: @item
 7478: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7479: time the parse area is emptied.
 7480: @item
 7481: If an error occurs, the input source is set back to the user input
 7482: device.
 7483: @end itemize
 7484: 
 7485: You can read about this in more detail in @ref{Input Sources}.
 7486: 
 7487: doc->in
 7488: doc-source
 7489: 
 7490: doc-tib
 7491: doc-#tib
 7492: 
 7493: 
 7494: @menu
 7495: * Input Sources::               
 7496: * Number Conversion::           
 7497: * Interpret/Compile states::    
 7498: * Interpreter Directives::      
 7499: @end menu
 7500: 
 7501: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7502: @subsection Input Sources
 7503: @cindex input sources
 7504: @cindex text interpreter - input sources
 7505: 
 7506: By default, the text interpreter processes input from the user input
 7507: device (the keyboard) when Forth starts up. The text interpreter can
 7508: process input from any of these sources:
 7509: 
 7510: @itemize @bullet
 7511: @item
 7512: The user input device -- the keyboard.
 7513: @item
 7514: A file, using the words described in @ref{Forth source files}.
 7515: @item
 7516: A block, using the words described in @ref{Blocks}.
 7517: @item
 7518: A text string, using @code{evaluate}.
 7519: @end itemize
 7520: 
 7521: A program can identify the current input device from the values of
 7522: @code{source-id} and @code{blk}.
 7523: 
 7524: 
 7525: doc-source-id
 7526: doc-blk
 7527: 
 7528: doc-save-input
 7529: doc-restore-input
 7530: 
 7531: doc-evaluate
 7532: doc-query
 7533: 
 7534: 
 7535: 
 7536: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7537: @subsection Number Conversion
 7538: @cindex number conversion
 7539: @cindex double-cell numbers, input format
 7540: @cindex input format for double-cell numbers
 7541: @cindex single-cell numbers, input format
 7542: @cindex input format for single-cell numbers
 7543: @cindex floating-point numbers, input format
 7544: @cindex input format for floating-point numbers
 7545: 
 7546: This section describes the rules that the text interpreter uses when it
 7547: tries to convert a string into a number.
 7548: 
 7549: Let <digit> represent any character that is a legal digit in the current
 7550: number base@footnote{For example, 0-9 when the number base is decimal or
 7551: 0-9, A-F when the number base is hexadecimal.}.
 7552: 
 7553: Let <decimal digit> represent any character in the range 0-9.
 7554: 
 7555: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7556: in the braces (@i{a} or @i{b} or neither).
 7557: 
 7558: Let * represent any number of instances of the previous character
 7559: (including none).
 7560: 
 7561: Let any other character represent itself.
 7562: 
 7563: @noindent
 7564: Now, the conversion rules are:
 7565: 
 7566: @itemize @bullet
 7567: @item
 7568: A string of the form <digit><digit>* is treated as a single-precision
 7569: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7570: @item
 7571: A string of the form -<digit><digit>* is treated as a single-precision
 7572: (cell-sized) negative integer, and is represented using 2's-complement
 7573: arithmetic. Examples are -45 -5681 -0
 7574: @item
 7575: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7576: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7577: (all three of these represent the same number).
 7578: @item
 7579: A string of the form -<digit><digit>*.<digit>* is treated as a
 7580: double-precision (double-cell-sized) negative integer, and is
 7581: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7582: -34.65 (all three of these represent the same number).
 7583: @item
 7584: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7585: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7586: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7587: number) +12.E-4
 7588: @end itemize
 7589: 
 7590: By default, the number base used for integer number conversion is given
 7591: by the contents of the variable @code{base}.  Note that a lot of
 7592: confusion can result from unexpected values of @code{base}.  If you
 7593: change @code{base} anywhere, make sure to save the old value and restore
 7594: it afterwards.  In general I recommend keeping @code{base} decimal, and
 7595: using the prefixes described below for the popular non-decimal bases.
 7596: 
 7597: doc-dpl
 7598: doc-base
 7599: doc-hex
 7600: doc-decimal
 7601: 
 7602: @cindex '-prefix for character strings
 7603: @cindex &-prefix for decimal numbers
 7604: @cindex #-prefix for decimal numbers
 7605: @cindex %-prefix for binary numbers
 7606: @cindex $-prefix for hexadecimal numbers
 7607: @cindex 0x-prefix for hexadecimal numbers
 7608: Gforth allows you to override the value of @code{base} by using a
 7609: prefix@footnote{Some Forth implementations provide a similar scheme by
 7610: implementing @code{$} etc. as parsing words that process the subsequent
 7611: number in the input stream and push it onto the stack. For example, see
 7612: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7613: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7614: is required between the prefix and the number.} before the first digit
 7615: of an (integer) number. The following prefixes are supported:
 7616: 
 7617: @itemize @bullet
 7618: @item
 7619: @code{&} -- decimal
 7620: @item
 7621: @code{#} -- decimal
 7622: @item
 7623: @code{%} -- binary
 7624: @item
 7625: @code{$} -- hexadecimal
 7626: @item
 7627: @code{0x} -- hexadecimal, if base<33.
 7628: @item
 7629: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 7630: optional @code{'} may be present after the character.
 7631: @end itemize
 7632: 
 7633: Here are some examples, with the equivalent decimal number shown after
 7634: in braces:
 7635: 
 7636: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7637: 'A (65),
 7638: -'a' (-97),
 7639: &905 (905), $abc (2478), $ABC (2478).
 7640: 
 7641: @cindex number conversion - traps for the unwary
 7642: @noindent
 7643: Number conversion has a number of traps for the unwary:
 7644: 
 7645: @itemize @bullet
 7646: @item
 7647: You cannot determine the current number base using the code sequence
 7648: @code{base @@ .} -- the number base is always 10 in the current number
 7649: base. Instead, use something like @code{base @@ dec.}
 7650: @item
 7651: If the number base is set to a value greater than 14 (for example,
 7652: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7653: it to be intepreted as either a single-precision integer or a
 7654: floating-point number (Gforth treats it as an integer). The ambiguity
 7655: can be resolved by explicitly stating the sign of the mantissa and/or
 7656: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7657: ambiguity arises; either representation will be treated as a
 7658: floating-point number.
 7659: @item
 7660: There is a word @code{bin} but it does @i{not} set the number base!
 7661: It is used to specify file types.
 7662: @item
 7663: ANS Forth requires the @code{.} of a double-precision number to be the
 7664: final character in the string.  Gforth allows the @code{.} to be
 7665: anywhere after the first digit.
 7666: @item
 7667: The number conversion process does not check for overflow.
 7668: @item
 7669: In an ANS Forth program @code{base} is required to be decimal when
 7670: converting floating-point numbers.  In Gforth, number conversion to
 7671: floating-point numbers always uses base &10, irrespective of the value
 7672: of @code{base}.
 7673: @end itemize
 7674: 
 7675: You can read numbers into your programs with the words described in
 7676: @ref{Input}.
 7677: 
 7678: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7679: @subsection Interpret/Compile states
 7680: @cindex Interpret/Compile states
 7681: 
 7682: A standard program is not permitted to change @code{state}
 7683: explicitly. However, it can change @code{state} implicitly, using the
 7684: words @code{[} and @code{]}. When @code{[} is executed it switches
 7685: @code{state} to interpret state, and therefore the text interpreter
 7686: starts interpreting. When @code{]} is executed it switches @code{state}
 7687: to compile state and therefore the text interpreter starts
 7688: compiling. The most common usage for these words is for switching into
 7689: interpret state and back from within a colon definition; this technique
 7690: can be used to compile a literal (for an example, @pxref{Literals}) or
 7691: for conditional compilation (for an example, @pxref{Interpreter
 7692: Directives}).
 7693: 
 7694: 
 7695: @c This is a bad example: It's non-standard, and it's not necessary.
 7696: @c However, I can't think of a good example for switching into compile
 7697: @c state when there is no current word (@code{state}-smart words are not a
 7698: @c good reason).  So maybe we should use an example for switching into
 7699: @c interpret @code{state} in a colon def. - anton
 7700: @c nac-> I agree. I started out by putting in the example, then realised
 7701: @c that it was non-ANS, so wrote more words around it. I hope this
 7702: @c re-written version is acceptable to you. I do want to keep the example
 7703: @c as it is helpful for showing what is and what is not portable, particularly
 7704: @c where it outlaws a style in common use.
 7705: 
 7706: @c anton: it's more important to show what's portable.  After we have done
 7707: @c that, we can also show what's not.  In any case, I have written a
 7708: @c section Compiling Words which also deals with [ ].
 7709: 
 7710: @c  !! The following example does not work in Gforth 0.5.9 or later.
 7711: 
 7712: @c  @code{[} and @code{]} also give you the ability to switch into compile
 7713: @c  state and back, but we cannot think of any useful Standard application
 7714: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 7715: 
 7716: @c  @example
 7717: @c  : AA ." this is A" ;
 7718: @c  : BB ." this is B" ;
 7719: @c  : CC ." this is C" ;
 7720: 
 7721: @c  create table ] aa bb cc [
 7722: 
 7723: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7724: @c    cells table + @@ execute ;
 7725: @c  @end example
 7726: 
 7727: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 7728: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7729: @c  defining @code{table} like this:
 7730: 
 7731: @c  @example
 7732: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7733: @c  @end example
 7734: 
 7735: @c  The problem with this code is that the definition of @code{table} is not
 7736: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 7737: @c  @i{may} work on systems where code space and data space co-incide, the
 7738: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 7739: @c  word. In addition, the Standard only allows @code{@@} to access data
 7740: @c  space, whilst this example is using it to access code space. The only
 7741: @c  portable, Standard way to build this table is to build it in data space,
 7742: @c  like this:
 7743: 
 7744: @c  @example
 7745: @c  create table ' aa , ' bb , ' cc ,
 7746: @c  @end example
 7747: 
 7748: @c  doc-state
 7749: 
 7750: 
 7751: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7752: @subsection Interpreter Directives
 7753: @cindex interpreter directives
 7754: @cindex conditional compilation
 7755: 
 7756: These words are usually used in interpret state; typically to control
 7757: which parts of a source file are processed by the text
 7758: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7759: supplements these with a rich set of immediate control structure words
 7760: to compensate for the fact that the non-immediate versions can only be
 7761: used in compile state (@pxref{Control Structures}). Typical usages:
 7762: 
 7763: @example
 7764: FALSE Constant HAVE-ASSEMBLER
 7765: .
 7766: .
 7767: HAVE-ASSEMBLER [IF]
 7768: : ASSEMBLER-FEATURE
 7769:   ...
 7770: ;
 7771: [ENDIF]
 7772: .
 7773: .
 7774: : SEE
 7775:   ... \ general-purpose SEE code
 7776:   [ HAVE-ASSEMBLER [IF] ]
 7777:   ... \ assembler-specific SEE code
 7778:   [ [ENDIF] ]
 7779: ;
 7780: @end example
 7781: 
 7782: 
 7783: doc-[IF]
 7784: doc-[ELSE]
 7785: doc-[THEN]
 7786: doc-[ENDIF]
 7787: 
 7788: doc-[IFDEF]
 7789: doc-[IFUNDEF]
 7790: 
 7791: doc-[?DO]
 7792: doc-[DO]
 7793: doc-[FOR]
 7794: doc-[LOOP]
 7795: doc-[+LOOP]
 7796: doc-[NEXT]
 7797: 
 7798: doc-[BEGIN]
 7799: doc-[UNTIL]
 7800: doc-[AGAIN]
 7801: doc-[WHILE]
 7802: doc-[REPEAT]
 7803: 
 7804: 
 7805: @c -------------------------------------------------------------
 7806: @node The Input Stream, Word Lists, The Text Interpreter, Words
 7807: @section The Input Stream
 7808: @cindex input stream
 7809: 
 7810: @c !! integrate this better with the "Text Interpreter" section
 7811: The text interpreter reads from the input stream, which can come from
 7812: several sources (@pxref{Input Sources}).  Some words, in particular
 7813: defining words, but also words like @code{'}, read parameters from the
 7814: input stream instead of from the stack.
 7815: 
 7816: Such words are called parsing words, because they parse the input
 7817: stream.  Parsing words are hard to use in other words, because it is
 7818: hard to pass program-generated parameters through the input stream.
 7819: They also usually have an unintuitive combination of interpretation and
 7820: compilation semantics when implemented naively, leading to various
 7821: approaches that try to produce a more intuitive behaviour
 7822: (@pxref{Combined words}).
 7823: 
 7824: It should be obvious by now that parsing words are a bad idea.  If you
 7825: want to implement a parsing word for convenience, also provide a factor
 7826: of the word that does not parse, but takes the parameters on the stack.
 7827: To implement the parsing word on top if it, you can use the following
 7828: words:
 7829: 
 7830: @c anton: these belong in the input stream section
 7831: doc-parse
 7832: doc-parse-name
 7833: doc-parse-word
 7834: doc-name
 7835: doc-word
 7836: doc-\"-parse
 7837: doc-refill
 7838: 
 7839: Conversely, if you have the bad luck (or lack of foresight) to have to
 7840: deal with parsing words without having such factors, how do you pass a
 7841: string that is not in the input stream to it?
 7842: 
 7843: doc-execute-parsing
 7844: 
 7845: If you want to run a parsing word on a file, the following word should
 7846: help:
 7847: 
 7848: doc-execute-parsing-file
 7849: 
 7850: @c -------------------------------------------------------------
 7851: @node Word Lists, Environmental Queries, The Input Stream, Words
 7852: @section Word Lists
 7853: @cindex word lists
 7854: @cindex header space
 7855: 
 7856: A wordlist is a list of named words; you can add new words and look up
 7857: words by name (and you can remove words in a restricted way with
 7858: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 7859: 
 7860: @cindex search order stack
 7861: The text interpreter searches the wordlists present in the search order
 7862: (a stack of wordlists), from the top to the bottom.  Within each
 7863: wordlist, the search starts conceptually at the newest word; i.e., if
 7864: two words in a wordlist have the same name, the newer word is found.
 7865: 
 7866: @cindex compilation word list
 7867: New words are added to the @dfn{compilation wordlist} (aka current
 7868: wordlist).
 7869: 
 7870: @cindex wid
 7871: A word list is identified by a cell-sized word list identifier (@i{wid})
 7872: in much the same way as a file is identified by a file handle. The
 7873: numerical value of the wid has no (portable) meaning, and might change
 7874: from session to session.
 7875: 
 7876: The ANS Forth ``Search order'' word set is intended to provide a set of
 7877: low-level tools that allow various different schemes to be
 7878: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 7879: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 7880: Forth.
 7881: 
 7882: @comment TODO: locals section refers to here, saying that every word list (aka
 7883: @comment vocabulary) has its own methods for searching etc. Need to document that.
 7884: @c anton: but better in a separate subsection on wordlist internals
 7885: 
 7886: @comment TODO: document markers, reveal, tables, mappedwordlist
 7887: 
 7888: @comment the gforthman- prefix is used to pick out the true definition of a
 7889: @comment word from the source files, rather than some alias.
 7890: 
 7891: doc-forth-wordlist
 7892: doc-definitions
 7893: doc-get-current
 7894: doc-set-current
 7895: doc-get-order
 7896: doc---gforthman-set-order
 7897: doc-wordlist
 7898: doc-table
 7899: doc->order
 7900: doc-previous
 7901: doc-also
 7902: doc---gforthman-forth
 7903: doc-only
 7904: doc---gforthman-order
 7905: 
 7906: doc-find
 7907: doc-search-wordlist
 7908: 
 7909: doc-words
 7910: doc-vlist
 7911: @c doc-words-deferred
 7912: 
 7913: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 7914: doc-root
 7915: doc-vocabulary
 7916: doc-seal
 7917: doc-vocs
 7918: doc-current
 7919: doc-context
 7920: 
 7921: 
 7922: @menu
 7923: * Vocabularies::                
 7924: * Why use word lists?::         
 7925: * Word list example::           
 7926: @end menu
 7927: 
 7928: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 7929: @subsection Vocabularies
 7930: @cindex Vocabularies, detailed explanation
 7931: 
 7932: Here is an example of creating and using a new wordlist using ANS
 7933: Forth words:
 7934: 
 7935: @example
 7936: wordlist constant my-new-words-wordlist
 7937: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 7938: 
 7939: \ add it to the search order
 7940: also my-new-words
 7941: 
 7942: \ alternatively, add it to the search order and make it
 7943: \ the compilation word list
 7944: also my-new-words definitions
 7945: \ type "order" to see the problem
 7946: @end example
 7947: 
 7948: The problem with this example is that @code{order} has no way to
 7949: associate the name @code{my-new-words} with the wid of the word list (in
 7950: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 7951: that has no associated name). There is no Standard way of associating a
 7952: name with a wid.
 7953: 
 7954: In Gforth, this example can be re-coded using @code{vocabulary}, which
 7955: associates a name with a wid:
 7956: 
 7957: @example
 7958: vocabulary my-new-words
 7959: 
 7960: \ add it to the search order
 7961: also my-new-words
 7962: 
 7963: \ alternatively, add it to the search order and make it
 7964: \ the compilation word list
 7965: my-new-words definitions
 7966: \ type "order" to see that the problem is solved
 7967: @end example
 7968: 
 7969: 
 7970: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 7971: @subsection Why use word lists?
 7972: @cindex word lists - why use them?
 7973: 
 7974: Here are some reasons why people use wordlists:
 7975: 
 7976: @itemize @bullet
 7977: 
 7978: @c anton: Gforth's hashing implementation makes the search speed
 7979: @c independent from the number of words.  But it is linear with the number
 7980: @c of wordlists that have to be searched, so in effect using more wordlists
 7981: @c actually slows down compilation.
 7982: 
 7983: @c @item
 7984: @c To improve compilation speed by reducing the number of header space
 7985: @c entries that must be searched. This is achieved by creating a new
 7986: @c word list that contains all of the definitions that are used in the
 7987: @c definition of a Forth system but which would not usually be used by
 7988: @c programs running on that system. That word list would be on the search
 7989: @c list when the Forth system was compiled but would be removed from the
 7990: @c search list for normal operation. This can be a useful technique for
 7991: @c low-performance systems (for example, 8-bit processors in embedded
 7992: @c systems) but is unlikely to be necessary in high-performance desktop
 7993: @c systems.
 7994: 
 7995: @item
 7996: To prevent a set of words from being used outside the context in which
 7997: they are valid. Two classic examples of this are an integrated editor
 7998: (all of the edit commands are defined in a separate word list; the
 7999: search order is set to the editor word list when the editor is invoked;
 8000: the old search order is restored when the editor is terminated) and an
 8001: integrated assembler (the op-codes for the machine are defined in a
 8002: separate word list which is used when a @code{CODE} word is defined).
 8003: 
 8004: @item
 8005: To organize the words of an application or library into a user-visible
 8006: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8007: of helper words used just for the implementation (hidden in a separate
 8008: wordlist).  This keeps @code{words}' output smaller, separates
 8009: implementation and interface, and reduces the chance of name conflicts
 8010: within the common wordlist.
 8011: 
 8012: @item
 8013: To prevent a name-space clash between multiple definitions with the same
 8014: name. For example, when building a cross-compiler you might have a word
 8015: @code{IF} that generates conditional code for your target system. By
 8016: placing this definition in a different word list you can control whether
 8017: the host system's @code{IF} or the target system's @code{IF} get used in
 8018: any particular context by controlling the order of the word lists on the
 8019: search order stack.
 8020: 
 8021: @end itemize
 8022: 
 8023: The downsides of using wordlists are:
 8024: 
 8025: @itemize
 8026: 
 8027: @item
 8028: Debugging becomes more cumbersome.
 8029: 
 8030: @item
 8031: Name conflicts worked around with wordlists are still there, and you
 8032: have to arrange the search order carefully to get the desired results;
 8033: if you forget to do that, you get hard-to-find errors (as in any case
 8034: where you read the code differently from the compiler; @code{see} can
 8035: help seeing which of several possible words the name resolves to in such
 8036: cases).  @code{See} displays just the name of the words, not what
 8037: wordlist they belong to, so it might be misleading.  Using unique names
 8038: is a better approach to avoid name conflicts.
 8039: 
 8040: @item
 8041: You have to explicitly undo any changes to the search order.  In many
 8042: cases it would be more convenient if this happened implicitly.  Gforth
 8043: currently does not provide such a feature, but it may do so in the
 8044: future.
 8045: @end itemize
 8046: 
 8047: 
 8048: @node Word list example,  , Why use word lists?, Word Lists
 8049: @subsection Word list example
 8050: @cindex word lists - example
 8051: 
 8052: The following example is from the
 8053: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8054: garbage collector} and uses wordlists to separate public words from
 8055: helper words:
 8056: 
 8057: @example
 8058: get-current ( wid )
 8059: vocabulary garbage-collector also garbage-collector definitions
 8060: ... \ define helper words
 8061: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8062: ... \ define the public (i.e., API) words
 8063:     \ they can refer to the helper words
 8064: previous \ restore original search order (helper words become invisible)
 8065: @end example
 8066: 
 8067: @c -------------------------------------------------------------
 8068: @node Environmental Queries, Files, Word Lists, Words
 8069: @section Environmental Queries
 8070: @cindex environmental queries
 8071: 
 8072: ANS Forth introduced the idea of ``environmental queries'' as a way
 8073: for a program running on a system to determine certain characteristics of the system.
 8074: The Standard specifies a number of strings that might be recognised by a system.
 8075: 
 8076: The Standard requires that the header space used for environmental queries
 8077: be distinct from the header space used for definitions.
 8078: 
 8079: Typically, environmental queries are supported by creating a set of
 8080: definitions in a word list that is @i{only} used during environmental
 8081: queries; that is what Gforth does. There is no Standard way of adding
 8082: definitions to the set of recognised environmental queries, but any
 8083: implementation that supports the loading of optional word sets must have
 8084: some mechanism for doing this (after loading the word set, the
 8085: associated environmental query string must return @code{true}). In
 8086: Gforth, the word list used to honour environmental queries can be
 8087: manipulated just like any other word list.
 8088: 
 8089: 
 8090: doc-environment?
 8091: doc-environment-wordlist
 8092: 
 8093: doc-gforth
 8094: doc-os-class
 8095: 
 8096: 
 8097: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8098: returning two items on the stack, querying it using @code{environment?}
 8099: will return an additional item; the @code{true} flag that shows that the
 8100: string was recognised.
 8101: 
 8102: @comment TODO Document the standard strings or note where they are documented herein
 8103: 
 8104: Here are some examples of using environmental queries:
 8105: 
 8106: @example
 8107: s" address-unit-bits" environment? 0=
 8108: [IF]
 8109:      cr .( environmental attribute address-units-bits unknown... ) cr
 8110: [ELSE]
 8111:      drop \ ensure balanced stack effect
 8112: [THEN]
 8113: 
 8114: \ this might occur in the prelude of a standard program that uses THROW
 8115: s" exception" environment? [IF]
 8116:    0= [IF]
 8117:       : throw abort" exception thrown" ;
 8118:    [THEN]
 8119: [ELSE] \ we don't know, so make sure
 8120:    : throw abort" exception thrown" ;
 8121: [THEN]
 8122: 
 8123: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8124:                         [ELSE] .( Not Gforth..) [THEN]
 8125: 
 8126: \ a program using v*
 8127: s" gforth" environment? [IF]
 8128:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8129:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8130:      >r swap 2swap swap 0e r> 0 ?DO
 8131:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
 8132:      LOOP
 8133:      2drop 2drop ; 
 8134:   [THEN]
 8135: [ELSE] \ 
 8136:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8137:   ...
 8138: [THEN]
 8139: @end example
 8140: 
 8141: Here is an example of adding a definition to the environment word list:
 8142: 
 8143: @example
 8144: get-current environment-wordlist set-current
 8145: true constant block
 8146: true constant block-ext
 8147: set-current
 8148: @end example
 8149: 
 8150: You can see what definitions are in the environment word list like this:
 8151: 
 8152: @example
 8153: environment-wordlist >order words previous
 8154: @end example
 8155: 
 8156: 
 8157: @c -------------------------------------------------------------
 8158: @node Files, Blocks, Environmental Queries, Words
 8159: @section Files
 8160: @cindex files
 8161: @cindex I/O - file-handling
 8162: 
 8163: Gforth provides facilities for accessing files that are stored in the
 8164: host operating system's file-system. Files that are processed by Gforth
 8165: can be divided into two categories:
 8166: 
 8167: @itemize @bullet
 8168: @item
 8169: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8170: @item
 8171: Files that are processed by some other program (@dfn{general files}).
 8172: @end itemize
 8173: 
 8174: @menu
 8175: * Forth source files::          
 8176: * General files::               
 8177: * Search Paths::                
 8178: @end menu
 8179: 
 8180: @c -------------------------------------------------------------
 8181: @node Forth source files, General files, Files, Files
 8182: @subsection Forth source files
 8183: @cindex including files
 8184: @cindex Forth source files
 8185: 
 8186: The simplest way to interpret the contents of a file is to use one of
 8187: these two formats:
 8188: 
 8189: @example
 8190: include mysource.fs
 8191: s" mysource.fs" included
 8192: @end example
 8193: 
 8194: You usually want to include a file only if it is not included already
 8195: (by, say, another source file). In that case, you can use one of these
 8196: three formats:
 8197: 
 8198: @example
 8199: require mysource.fs
 8200: needs mysource.fs
 8201: s" mysource.fs" required
 8202: @end example
 8203: 
 8204: @cindex stack effect of included files
 8205: @cindex including files, stack effect
 8206: It is good practice to write your source files such that interpreting them
 8207: does not change the stack. Source files designed in this way can be used with
 8208: @code{required} and friends without complications. For example:
 8209: 
 8210: @example
 8211: 1024 require foo.fs drop
 8212: @end example
 8213: 
 8214: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8215: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8216: ), which allows its use with @code{require}.  Of course with such
 8217: parameters to required files, you have to ensure that the first
 8218: @code{require} fits for all uses (i.e., @code{require} it early in the
 8219: master load file).
 8220: 
 8221: doc-include-file
 8222: doc-included
 8223: doc-included?
 8224: doc-include
 8225: doc-required
 8226: doc-require
 8227: doc-needs
 8228: @c doc-init-included-files @c internal
 8229: doc-sourcefilename
 8230: doc-sourceline#
 8231: 
 8232: A definition in ANS Forth for @code{required} is provided in
 8233: @file{compat/required.fs}.
 8234: 
 8235: @c -------------------------------------------------------------
 8236: @node General files, Search Paths, Forth source files, Files
 8237: @subsection General files
 8238: @cindex general files
 8239: @cindex file-handling
 8240: 
 8241: Files are opened/created by name and type. The following file access
 8242: methods (FAMs) are recognised:
 8243: 
 8244: @cindex fam (file access method)
 8245: doc-r/o
 8246: doc-r/w
 8247: doc-w/o
 8248: doc-bin
 8249: 
 8250: 
 8251: When a file is opened/created, it returns a file identifier,
 8252: @i{wfileid} that is used for all other file commands. All file
 8253: commands also return a status value, @i{wior}, that is 0 for a
 8254: successful operation and an implementation-defined non-zero value in the
 8255: case of an error.
 8256: 
 8257: 
 8258: doc-open-file
 8259: doc-create-file
 8260: 
 8261: doc-close-file
 8262: doc-delete-file
 8263: doc-rename-file
 8264: doc-read-file
 8265: doc-read-line
 8266: doc-write-file
 8267: doc-write-line
 8268: doc-emit-file
 8269: doc-flush-file
 8270: 
 8271: doc-file-status
 8272: doc-file-position
 8273: doc-reposition-file
 8274: doc-file-size
 8275: doc-resize-file
 8276: 
 8277: doc-slurp-file
 8278: doc-slurp-fid
 8279: doc-stdin
 8280: doc-stdout
 8281: doc-stderr
 8282: 
 8283: @c ---------------------------------------------------------
 8284: @node Search Paths,  , General files, Files
 8285: @subsection Search Paths
 8286: @cindex path for @code{included}
 8287: @cindex file search path
 8288: @cindex @code{include} search path
 8289: @cindex search path for files
 8290: 
 8291: If you specify an absolute filename (i.e., a filename starting with
 8292: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8293: @samp{C:...})) for @code{included} and friends, that file is included
 8294: just as you would expect.
 8295: 
 8296: If the filename starts with @file{./}, this refers to the directory that
 8297: the present file was @code{included} from.  This allows files to include
 8298: other files relative to their own position (irrespective of the current
 8299: working directory or the absolute position).  This feature is essential
 8300: for libraries consisting of several files, where a file may include
 8301: other files from the library.  It corresponds to @code{#include "..."}
 8302: in C. If the current input source is not a file, @file{.} refers to the
 8303: directory of the innermost file being included, or, if there is no file
 8304: being included, to the current working directory.
 8305: 
 8306: For relative filenames (not starting with @file{./}), Gforth uses a
 8307: search path similar to Forth's search order (@pxref{Word Lists}). It
 8308: tries to find the given filename in the directories present in the path,
 8309: and includes the first one it finds. There are separate search paths for
 8310: Forth source files and general files.  If the search path contains the
 8311: directory @file{.}, this refers to the directory of the current file, or
 8312: the working directory, as if the file had been specified with @file{./}.
 8313: 
 8314: Use @file{~+} to refer to the current working directory (as in the
 8315: @code{bash}).
 8316: 
 8317: @c anton: fold the following subsubsections into this subsection?
 8318: 
 8319: @menu
 8320: * Source Search Paths::         
 8321: * General Search Paths::        
 8322: @end menu
 8323: 
 8324: @c ---------------------------------------------------------
 8325: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8326: @subsubsection Source Search Paths
 8327: @cindex search path control, source files
 8328: 
 8329: The search path is initialized when you start Gforth (@pxref{Invoking
 8330: Gforth}). You can display it and change it using @code{fpath} in
 8331: combination with the general path handling words.
 8332: 
 8333: doc-fpath
 8334: @c the functionality of the following words is easily available through
 8335: @c   fpath and the general path words.  The may go away.
 8336: @c doc-.fpath
 8337: @c doc-fpath+
 8338: @c doc-fpath=
 8339: @c doc-open-fpath-file
 8340: 
 8341: @noindent
 8342: Here is an example of using @code{fpath} and @code{require}:
 8343: 
 8344: @example
 8345: fpath path= /usr/lib/forth/|./
 8346: require timer.fs
 8347: @end example
 8348: 
 8349: 
 8350: @c ---------------------------------------------------------
 8351: @node General Search Paths,  , Source Search Paths, Search Paths
 8352: @subsubsection General Search Paths
 8353: @cindex search path control, source files
 8354: 
 8355: Your application may need to search files in several directories, like
 8356: @code{included} does. To facilitate this, Gforth allows you to define
 8357: and use your own search paths, by providing generic equivalents of the
 8358: Forth search path words:
 8359: 
 8360: doc-open-path-file
 8361: doc-path-allot
 8362: doc-clear-path
 8363: doc-also-path
 8364: doc-.path
 8365: doc-path+
 8366: doc-path=
 8367: 
 8368: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8369: 
 8370: Here's an example of creating an empty search path:
 8371: @c
 8372: @example
 8373: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8374: @end example
 8375: 
 8376: @c -------------------------------------------------------------
 8377: @node Blocks, Other I/O, Files, Words
 8378: @section Blocks
 8379: @cindex I/O - blocks
 8380: @cindex blocks
 8381: 
 8382: When you run Gforth on a modern desk-top computer, it runs under the
 8383: control of an operating system which provides certain services.  One of
 8384: these services is @var{file services}, which allows Forth source code
 8385: and data to be stored in files and read into Gforth (@pxref{Files}).
 8386: 
 8387: Traditionally, Forth has been an important programming language on
 8388: systems where it has interfaced directly to the underlying hardware with
 8389: no intervening operating system. Forth provides a mechanism, called
 8390: @dfn{blocks}, for accessing mass storage on such systems.
 8391: 
 8392: A block is a 1024-byte data area, which can be used to hold data or
 8393: Forth source code. No structure is imposed on the contents of the
 8394: block. A block is identified by its number; blocks are numbered
 8395: contiguously from 1 to an implementation-defined maximum.
 8396: 
 8397: A typical system that used blocks but no operating system might use a
 8398: single floppy-disk drive for mass storage, with the disks formatted to
 8399: provide 256-byte sectors. Blocks would be implemented by assigning the
 8400: first four sectors of the disk to block 1, the second four sectors to
 8401: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8402: would not contain any file system information, just the set of blocks.
 8403: 
 8404: @cindex blocks file
 8405: On systems that do provide file services, blocks are typically
 8406: implemented by storing a sequence of blocks within a single @dfn{blocks
 8407: file}.  The size of the blocks file will be an exact multiple of 1024
 8408: bytes, corresponding to the number of blocks it contains. This is the
 8409: mechanism that Gforth uses.
 8410: 
 8411: @cindex @file{blocks.fb}
 8412: Only one blocks file can be open at a time. If you use block words without
 8413: having specified a blocks file, Gforth defaults to the blocks file
 8414: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8415: locate a blocks file (@pxref{Source Search Paths}).
 8416: 
 8417: @cindex block buffers
 8418: When you read and write blocks under program control, Gforth uses a
 8419: number of @dfn{block buffers} as intermediate storage. These buffers are
 8420: not used when you use @code{load} to interpret the contents of a block.
 8421: 
 8422: The behaviour of the block buffers is analagous to that of a cache.
 8423: Each block buffer has three states:
 8424: 
 8425: @itemize @bullet
 8426: @item
 8427: Unassigned
 8428: @item
 8429: Assigned-clean
 8430: @item
 8431: Assigned-dirty
 8432: @end itemize
 8433: 
 8434: Initially, all block buffers are @i{unassigned}. In order to access a
 8435: block, the block (specified by its block number) must be assigned to a
 8436: block buffer.
 8437: 
 8438: The assignment of a block to a block buffer is performed by @code{block}
 8439: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8440: contents of a block. Use @code{buffer} when you don't care about the
 8441: existing contents of the block@footnote{The ANS Forth definition of
 8442: @code{buffer} is intended not to cause disk I/O; if the data associated
 8443: with the particular block is already stored in a block buffer due to an
 8444: earlier @code{block} command, @code{buffer} will return that block
 8445: buffer and the existing contents of the block will be
 8446: available. Otherwise, @code{buffer} will simply assign a new, empty
 8447: block buffer for the block.}.
 8448: 
 8449: Once a block has been assigned to a block buffer using @code{block} or
 8450: @code{buffer}, that block buffer becomes the @i{current block
 8451: buffer}. Data may only be manipulated (read or written) within the
 8452: current block buffer.
 8453: 
 8454: When the contents of the current block buffer has been modified it is
 8455: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8456: either abandon the changes (by doing nothing) or mark the block as
 8457: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8458: not change the blocks file; it simply changes a block buffer's state to
 8459: @i{assigned-dirty}.  The block will be written implicitly when it's
 8460: buffer is needed for another block, or explicitly by @code{flush} or
 8461: @code{save-buffers}.
 8462: 
 8463: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8464: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8465: @code{flush}.
 8466: 
 8467: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8468: algorithm to assign a block buffer to a block. That means that any
 8469: particular block can only be assigned to one specific block buffer,
 8470: called (for the particular operation) the @i{victim buffer}. If the
 8471: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8472: the new block immediately. If it is @i{assigned-dirty} its current
 8473: contents are written back to the blocks file on disk before it is
 8474: allocated to the new block.
 8475: 
 8476: Although no structure is imposed on the contents of a block, it is
 8477: traditional to display the contents as 16 lines each of 64 characters.  A
 8478: block provides a single, continuous stream of input (for example, it
 8479: acts as a single parse area) -- there are no end-of-line characters
 8480: within a block, and no end-of-file character at the end of a
 8481: block. There are two consequences of this:
 8482: 
 8483: @itemize @bullet
 8484: @item
 8485: The last character of one line wraps straight into the first character
 8486: of the following line
 8487: @item
 8488: The word @code{\} -- comment to end of line -- requires special
 8489: treatment; in the context of a block it causes all characters until the
 8490: end of the current 64-character ``line'' to be ignored.
 8491: @end itemize
 8492: 
 8493: In Gforth, when you use @code{block} with a non-existent block number,
 8494: the current blocks file will be extended to the appropriate size and the
 8495: block buffer will be initialised with spaces.
 8496: 
 8497: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8498: for details) but doesn't encourage the use of blocks; the mechanism is
 8499: only provided for backward compatibility -- ANS Forth requires blocks to
 8500: be available when files are.
 8501: 
 8502: Common techniques that are used when working with blocks include:
 8503: 
 8504: @itemize @bullet
 8505: @item
 8506: A screen editor that allows you to edit blocks without leaving the Forth
 8507: environment.
 8508: @item
 8509: Shadow screens; where every code block has an associated block
 8510: containing comments (for example: code in odd block numbers, comments in
 8511: even block numbers). Typically, the block editor provides a convenient
 8512: mechanism to toggle between code and comments.
 8513: @item
 8514: Load blocks; a single block (typically block 1) contains a number of
 8515: @code{thru} commands which @code{load} the whole of the application.
 8516: @end itemize
 8517: 
 8518: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8519: integrated into a Forth programming environment.
 8520: 
 8521: @comment TODO what about errors on open-blocks?
 8522: 
 8523: doc-open-blocks
 8524: doc-use
 8525: doc-block-offset
 8526: doc-get-block-fid
 8527: doc-block-position
 8528: 
 8529: doc-list
 8530: doc-scr
 8531: 
 8532: doc---gforthman-block
 8533: doc-buffer
 8534: 
 8535: doc-empty-buffers
 8536: doc-empty-buffer
 8537: doc-update
 8538: doc-updated?
 8539: doc-save-buffers
 8540: doc-save-buffer
 8541: doc-flush
 8542: 
 8543: doc-load
 8544: doc-thru
 8545: doc-+load
 8546: doc-+thru
 8547: doc---gforthman--->
 8548: doc-block-included
 8549: 
 8550: 
 8551: @c -------------------------------------------------------------
 8552: @node Other I/O, OS command line arguments, Blocks, Words
 8553: @section Other I/O
 8554: @cindex I/O - keyboard and display
 8555: 
 8556: @menu
 8557: * Simple numeric output::       Predefined formats
 8558: * Formatted numeric output::    Formatted (pictured) output
 8559: * String Formats::              How Forth stores strings in memory
 8560: * Displaying characters and strings::  Other stuff
 8561: * Input::                       Input
 8562: * Pipes::                       How to create your own pipes
 8563: @end menu
 8564: 
 8565: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8566: @subsection Simple numeric output
 8567: @cindex numeric output - simple/free-format
 8568: 
 8569: The simplest output functions are those that display numbers from the
 8570: data or floating-point stacks. Floating-point output is always displayed
 8571: using base 10. Numbers displayed from the data stack use the value stored
 8572: in @code{base}.
 8573: 
 8574: 
 8575: doc-.
 8576: doc-dec.
 8577: doc-hex.
 8578: doc-u.
 8579: doc-.r
 8580: doc-u.r
 8581: doc-d.
 8582: doc-ud.
 8583: doc-d.r
 8584: doc-ud.r
 8585: doc-f.
 8586: doc-fe.
 8587: doc-fs.
 8588: doc-f.rdp
 8589: 
 8590: Examples of printing the number 1234.5678E23 in the different floating-point output
 8591: formats are shown below:
 8592: 
 8593: @example
 8594: f. 123456779999999000000000000.
 8595: fe. 123.456779999999E24
 8596: fs. 1.23456779999999E26
 8597: @end example
 8598: 
 8599: 
 8600: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8601: @subsection Formatted numeric output
 8602: @cindex formatted numeric output
 8603: @cindex pictured numeric output
 8604: @cindex numeric output - formatted
 8605: 
 8606: Forth traditionally uses a technique called @dfn{pictured numeric
 8607: output} for formatted printing of integers.  In this technique, digits
 8608: are extracted from the number (using the current output radix defined by
 8609: @code{base}), converted to ASCII codes and appended to a string that is
 8610: built in a scratch-pad area of memory (@pxref{core-idef,
 8611: Implementation-defined options, Implementation-defined
 8612: options}). Arbitrary characters can be appended to the string during the
 8613: extraction process. The completed string is specified by an address
 8614: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8615: under program control.
 8616: 
 8617: All of the integer output words described in the previous section
 8618: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8619: numeric output.
 8620: 
 8621: Three important things to remember about pictured numeric output:
 8622: 
 8623: @itemize @bullet
 8624: @item
 8625: It always operates on double-precision numbers; to display a
 8626: single-precision number, convert it first (for ways of doing this
 8627: @pxref{Double precision}).
 8628: @item
 8629: It always treats the double-precision number as though it were
 8630: unsigned. The examples below show ways of printing signed numbers.
 8631: @item
 8632: The string is built up from right to left; least significant digit first.
 8633: @end itemize
 8634: 
 8635: 
 8636: doc-<#
 8637: doc-<<#
 8638: doc-#
 8639: doc-#s
 8640: doc-hold
 8641: doc-sign
 8642: doc-#>
 8643: doc-#>>
 8644: 
 8645: doc-represent
 8646: doc-f>str-rdp
 8647: doc-f>buf-rdp
 8648: 
 8649: 
 8650: @noindent
 8651: Here are some examples of using pictured numeric output:
 8652: 
 8653: @example
 8654: : my-u. ( u -- )
 8655:   \ Simplest use of pns.. behaves like Standard u. 
 8656:   0              \ convert to unsigned double
 8657:   <<#            \ start conversion
 8658:   #s             \ convert all digits
 8659:   #>             \ complete conversion
 8660:   TYPE SPACE     \ display, with trailing space
 8661:   #>> ;          \ release hold area
 8662: 
 8663: : cents-only ( u -- )
 8664:   0              \ convert to unsigned double
 8665:   <<#            \ start conversion
 8666:   # #            \ convert two least-significant digits
 8667:   #>             \ complete conversion, discard other digits
 8668:   TYPE SPACE     \ display, with trailing space
 8669:   #>> ;          \ release hold area
 8670: 
 8671: : dollars-and-cents ( u -- )
 8672:   0              \ convert to unsigned double
 8673:   <<#            \ start conversion
 8674:   # #            \ convert two least-significant digits
 8675:   [char] . hold  \ insert decimal point
 8676:   #s             \ convert remaining digits
 8677:   [char] $ hold  \ append currency symbol
 8678:   #>             \ complete conversion
 8679:   TYPE SPACE     \ display, with trailing space
 8680:   #>> ;          \ release hold area
 8681: 
 8682: : my-. ( n -- )
 8683:   \ handling negatives.. behaves like Standard .
 8684:   s>d            \ convert to signed double
 8685:   swap over dabs \ leave sign byte followed by unsigned double
 8686:   <<#            \ start conversion
 8687:   #s             \ convert all digits
 8688:   rot sign       \ get at sign byte, append "-" if needed
 8689:   #>             \ complete conversion
 8690:   TYPE SPACE     \ display, with trailing space
 8691:   #>> ;          \ release hold area
 8692: 
 8693: : account. ( n -- )
 8694:   \ accountants don't like minus signs, they use parentheses
 8695:   \ for negative numbers
 8696:   s>d            \ convert to signed double
 8697:   swap over dabs \ leave sign byte followed by unsigned double
 8698:   <<#            \ start conversion
 8699:   2 pick         \ get copy of sign byte
 8700:   0< IF [char] ) hold THEN \ right-most character of output
 8701:   #s             \ convert all digits
 8702:   rot            \ get at sign byte
 8703:   0< IF [char] ( hold THEN
 8704:   #>             \ complete conversion
 8705:   TYPE SPACE     \ display, with trailing space
 8706:   #>> ;          \ release hold area
 8707: 
 8708: @end example
 8709: 
 8710: Here are some examples of using these words:
 8711: 
 8712: @example
 8713: 1 my-u. 1
 8714: hex -1 my-u. decimal FFFFFFFF
 8715: 1 cents-only 01
 8716: 1234 cents-only 34
 8717: 2 dollars-and-cents $0.02
 8718: 1234 dollars-and-cents $12.34
 8719: 123 my-. 123
 8720: -123 my. -123
 8721: 123 account. 123
 8722: -456 account. (456)
 8723: @end example
 8724: 
 8725: 
 8726: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8727: @subsection String Formats
 8728: @cindex strings - see character strings
 8729: @cindex character strings - formats
 8730: @cindex I/O - see character strings
 8731: @cindex counted strings
 8732: 
 8733: @c anton: this does not really belong here; maybe the memory section,
 8734: @c  or the principles chapter
 8735: 
 8736: Forth commonly uses two different methods for representing character
 8737: strings:
 8738: 
 8739: @itemize @bullet
 8740: @item
 8741: @cindex address of counted string
 8742: @cindex counted string
 8743: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8744: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8745: string and the string occupies the subsequent @i{n} char addresses in
 8746: memory.
 8747: @item
 8748: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8749: of the string in characters, and @i{c-addr} is the address of the
 8750: first byte of the string.
 8751: @end itemize
 8752: 
 8753: ANS Forth encourages the use of the second format when representing
 8754: strings.
 8755: 
 8756: 
 8757: doc-count
 8758: 
 8759: 
 8760: For words that move, copy and search for strings see @ref{Memory
 8761: Blocks}. For words that display characters and strings see
 8762: @ref{Displaying characters and strings}.
 8763: 
 8764: @node Displaying characters and strings, Input, String Formats, Other I/O
 8765: @subsection Displaying characters and strings
 8766: @cindex characters - compiling and displaying
 8767: @cindex character strings - compiling and displaying
 8768: 
 8769: This section starts with a glossary of Forth words and ends with a set
 8770: of examples.
 8771: 
 8772: 
 8773: doc-bl
 8774: doc-space
 8775: doc-spaces
 8776: doc-emit
 8777: doc-toupper
 8778: doc-."
 8779: doc-.(
 8780: doc-.\"
 8781: doc-type
 8782: doc-typewhite
 8783: doc-cr
 8784: @cindex cursor control
 8785: doc-at-xy
 8786: doc-page
 8787: doc-s"
 8788: doc-s\"
 8789: doc-c"
 8790: doc-char
 8791: doc-[char]
 8792: 
 8793: 
 8794: @noindent
 8795: As an example, consider the following text, stored in a file @file{test.fs}:
 8796: 
 8797: @example
 8798: .( text-1)
 8799: : my-word
 8800:   ." text-2" cr
 8801:   .( text-3)
 8802: ;
 8803: 
 8804: ." text-4"
 8805: 
 8806: : my-char
 8807:   [char] ALPHABET emit
 8808:   char emit
 8809: ;
 8810: @end example
 8811: 
 8812: When you load this code into Gforth, the following output is generated:
 8813: 
 8814: @example
 8815: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8816: @end example
 8817: 
 8818: @itemize @bullet
 8819: @item
 8820: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8821: is an immediate word; it behaves in the same way whether it is used inside
 8822: or outside a colon definition.
 8823: @item
 8824: Message @code{text-4} is displayed because of Gforth's added interpretation
 8825: semantics for @code{."}.
 8826: @item
 8827: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8828: performs the compilation semantics for @code{."} within the definition of
 8829: @code{my-word}.
 8830: @end itemize
 8831: 
 8832: Here are some examples of executing @code{my-word} and @code{my-char}:
 8833: 
 8834: @example
 8835: @kbd{my-word @key{RET}} text-2
 8836:  ok
 8837: @kbd{my-char fred @key{RET}} Af ok
 8838: @kbd{my-char jim @key{RET}} Aj ok
 8839: @end example
 8840: 
 8841: @itemize @bullet
 8842: @item
 8843: Message @code{text-2} is displayed because of the run-time behaviour of
 8844: @code{."}.
 8845: @item
 8846: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 8847: on the stack at run-time. @code{emit} always displays the character
 8848: when @code{my-char} is executed.
 8849: @item
 8850: @code{char} parses a string at run-time and the second @code{emit} displays
 8851: the first character of the string.
 8852: @item
 8853: If you type @code{see my-char} you can see that @code{[char]} discarded
 8854: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 8855: definition of @code{my-char}.
 8856: @end itemize
 8857: 
 8858: 
 8859: 
 8860: @node Input, Pipes, Displaying characters and strings, Other I/O
 8861: @subsection Input
 8862: @cindex input
 8863: @cindex I/O - see input
 8864: @cindex parsing a string
 8865: 
 8866: For ways of storing character strings in memory see @ref{String Formats}.
 8867: 
 8868: @comment TODO examples for >number >float accept key key? pad parse word refill
 8869: @comment then index them
 8870: 
 8871: 
 8872: doc-key
 8873: doc-key?
 8874: doc-ekey
 8875: doc-ekey?
 8876: doc-ekey>char
 8877: doc->number
 8878: doc->float
 8879: doc-accept
 8880: doc-edit-line
 8881: doc-pad
 8882: @comment obsolescent words..
 8883: doc-convert
 8884: doc-expect
 8885: doc-span
 8886: 
 8887: 
 8888: @node Pipes,  , Input, Other I/O
 8889: @subsection Pipes
 8890: @cindex pipes, creating your own
 8891: 
 8892: In addition to using Gforth in pipes created by other processes
 8893: (@pxref{Gforth in pipes}), you can create your own pipe with
 8894: @code{open-pipe}, and read from or write to it.
 8895: 
 8896: doc-open-pipe
 8897: doc-close-pipe
 8898: 
 8899: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 8900: you don't catch this exception, Gforth will catch it and exit, usually
 8901: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 8902: this, you should wrap a @code{catch} or @code{try} block around the code
 8903: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 8904: problem yourself, and then return to regular processing.
 8905: 
 8906: doc-broken-pipe-error
 8907: 
 8908: 
 8909: @node OS command line arguments, Locals, Other I/O, Words
 8910: @section OS command line arguments
 8911: @cindex OS command line arguments
 8912: @cindex command line arguments, OS
 8913: @cindex arguments, OS command line
 8914: 
 8915: The usual way to pass arguments to Gforth programs on the command line
 8916: is via the @option{-e} option, e.g.
 8917: 
 8918: @example
 8919: gforth -e "123 456" foo.fs -e bye
 8920: @end example
 8921: 
 8922: However, you may want to interpret the command-line arguments directly.
 8923: In that case, you can access the (image-specific) command-line arguments
 8924: through @code{next-arg}:
 8925: 
 8926: doc-next-arg
 8927: 
 8928: Here's an example program @file{echo.fs} for @code{next-arg}:
 8929: 
 8930: @example
 8931: : echo ( -- )
 8932:     begin
 8933: 	next-arg 2dup 0 0 d<> while
 8934: 	    type space
 8935:     repeat
 8936:     2drop ;
 8937: 
 8938: echo cr bye
 8939: @end example
 8940: 
 8941: This can be invoked with
 8942: 
 8943: @example
 8944: gforth echo.fs hello world
 8945: @end example
 8946: 
 8947: and it will print
 8948: 
 8949: @example
 8950: hello world
 8951: @end example
 8952: 
 8953: The next lower level of dealing with the OS command line are the
 8954: following words:
 8955: 
 8956: doc-arg
 8957: doc-shift-args
 8958: 
 8959: Finally, at the lowest level Gforth provides the following words:
 8960: 
 8961: doc-argc
 8962: doc-argv
 8963: 
 8964: @c -------------------------------------------------------------
 8965: @node Locals, Structures, OS command line arguments, Words
 8966: @section Locals
 8967: @cindex locals
 8968: 
 8969: Local variables can make Forth programming more enjoyable and Forth
 8970: programs easier to read. Unfortunately, the locals of ANS Forth are
 8971: laden with restrictions. Therefore, we provide not only the ANS Forth
 8972: locals wordset, but also our own, more powerful locals wordset (we
 8973: implemented the ANS Forth locals wordset through our locals wordset).
 8974: 
 8975: The ideas in this section have also been published in M. Anton Ertl,
 8976: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 8977: Automatic Scoping of Local Variables}}, EuroForth '94.
 8978: 
 8979: @menu
 8980: * Gforth locals::               
 8981: * ANS Forth locals::            
 8982: @end menu
 8983: 
 8984: @node Gforth locals, ANS Forth locals, Locals, Locals
 8985: @subsection Gforth locals
 8986: @cindex Gforth locals
 8987: @cindex locals, Gforth style
 8988: 
 8989: Locals can be defined with
 8990: 
 8991: @example
 8992: @{ local1 local2 ... -- comment @}
 8993: @end example
 8994: or
 8995: @example
 8996: @{ local1 local2 ... @}
 8997: @end example
 8998: 
 8999: E.g.,
 9000: @example
 9001: : max @{ n1 n2 -- n3 @}
 9002:  n1 n2 > if
 9003:    n1
 9004:  else
 9005:    n2
 9006:  endif ;
 9007: @end example
 9008: 
 9009: The similarity of locals definitions with stack comments is intended. A
 9010: locals definition often replaces the stack comment of a word. The order
 9011: of the locals corresponds to the order in a stack comment and everything
 9012: after the @code{--} is really a comment.
 9013: 
 9014: This similarity has one disadvantage: It is too easy to confuse locals
 9015: declarations with stack comments, causing bugs and making them hard to
 9016: find. However, this problem can be avoided by appropriate coding
 9017: conventions: Do not use both notations in the same program. If you do,
 9018: they should be distinguished using additional means, e.g. by position.
 9019: 
 9020: @cindex types of locals
 9021: @cindex locals types
 9022: The name of the local may be preceded by a type specifier, e.g.,
 9023: @code{F:} for a floating point value:
 9024: 
 9025: @example
 9026: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9027: \ complex multiplication
 9028:  Ar Br f* Ai Bi f* f-
 9029:  Ar Bi f* Ai Br f* f+ ;
 9030: @end example
 9031: 
 9032: @cindex flavours of locals
 9033: @cindex locals flavours
 9034: @cindex value-flavoured locals
 9035: @cindex variable-flavoured locals
 9036: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9037: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9038: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9039: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9040: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9041: produces its address (which becomes invalid when the variable's scope is
 9042: left). E.g., the standard word @code{emit} can be defined in terms of
 9043: @code{type} like this:
 9044: 
 9045: @example
 9046: : emit @{ C^ char* -- @}
 9047:     char* 1 type ;
 9048: @end example
 9049: 
 9050: @cindex default type of locals
 9051: @cindex locals, default type
 9052: A local without type specifier is a @code{W:} local. Both flavours of
 9053: locals are initialized with values from the data or FP stack.
 9054: 
 9055: Currently there is no way to define locals with user-defined data
 9056: structures, but we are working on it.
 9057: 
 9058: Gforth allows defining locals everywhere in a colon definition. This
 9059: poses the following questions:
 9060: 
 9061: @menu
 9062: * Where are locals visible by name?::  
 9063: * How long do locals live?::    
 9064: * Locals programming style::    
 9065: * Locals implementation::       
 9066: @end menu
 9067: 
 9068: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9069: @subsubsection Where are locals visible by name?
 9070: @cindex locals visibility
 9071: @cindex visibility of locals
 9072: @cindex scope of locals
 9073: 
 9074: Basically, the answer is that locals are visible where you would expect
 9075: it in block-structured languages, and sometimes a little longer. If you
 9076: want to restrict the scope of a local, enclose its definition in
 9077: @code{SCOPE}...@code{ENDSCOPE}.
 9078: 
 9079: 
 9080: doc-scope
 9081: doc-endscope
 9082: 
 9083: 
 9084: These words behave like control structure words, so you can use them
 9085: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9086: arbitrary ways.
 9087: 
 9088: If you want a more exact answer to the visibility question, here's the
 9089: basic principle: A local is visible in all places that can only be
 9090: reached through the definition of the local@footnote{In compiler
 9091: construction terminology, all places dominated by the definition of the
 9092: local.}. In other words, it is not visible in places that can be reached
 9093: without going through the definition of the local. E.g., locals defined
 9094: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9095: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9096: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9097: 
 9098: The reasoning behind this solution is: We want to have the locals
 9099: visible as long as it is meaningful. The user can always make the
 9100: visibility shorter by using explicit scoping. In a place that can
 9101: only be reached through the definition of a local, the meaning of a
 9102: local name is clear. In other places it is not: How is the local
 9103: initialized at the control flow path that does not contain the
 9104: definition? Which local is meant, if the same name is defined twice in
 9105: two independent control flow paths?
 9106: 
 9107: This should be enough detail for nearly all users, so you can skip the
 9108: rest of this section. If you really must know all the gory details and
 9109: options, read on.
 9110: 
 9111: In order to implement this rule, the compiler has to know which places
 9112: are unreachable. It knows this automatically after @code{AHEAD},
 9113: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9114: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9115: compiler that the control flow never reaches that place. If
 9116: @code{UNREACHABLE} is not used where it could, the only consequence is
 9117: that the visibility of some locals is more limited than the rule above
 9118: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9119: lie to the compiler), buggy code will be produced.
 9120: 
 9121: 
 9122: doc-unreachable
 9123: 
 9124: 
 9125: Another problem with this rule is that at @code{BEGIN}, the compiler
 9126: does not know which locals will be visible on the incoming
 9127: back-edge. All problems discussed in the following are due to this
 9128: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9129: loops as examples; the discussion also applies to @code{?DO} and other
 9130: loops). Perhaps the most insidious example is:
 9131: @example
 9132: AHEAD
 9133: BEGIN
 9134:   x
 9135: [ 1 CS-ROLL ] THEN
 9136:   @{ x @}
 9137:   ...
 9138: UNTIL
 9139: @end example
 9140: 
 9141: This should be legal according to the visibility rule. The use of
 9142: @code{x} can only be reached through the definition; but that appears
 9143: textually below the use.
 9144: 
 9145: From this example it is clear that the visibility rules cannot be fully
 9146: implemented without major headaches. Our implementation treats common
 9147: cases as advertised and the exceptions are treated in a safe way: The
 9148: compiler makes a reasonable guess about the locals visible after a
 9149: @code{BEGIN}; if it is too pessimistic, the
 9150: user will get a spurious error about the local not being defined; if the
 9151: compiler is too optimistic, it will notice this later and issue a
 9152: warning. In the case above the compiler would complain about @code{x}
 9153: being undefined at its use. You can see from the obscure examples in
 9154: this section that it takes quite unusual control structures to get the
 9155: compiler into trouble, and even then it will often do fine.
 9156: 
 9157: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9158: is that all locals visible before the @code{BEGIN} will also be
 9159: visible after the @code{BEGIN}. This guess is valid for all loops that
 9160: are entered only through the @code{BEGIN}, in particular, for normal
 9161: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9162: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9163: compiler. When the branch to the @code{BEGIN} is finally generated by
 9164: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9165: warns the user if it was too optimistic:
 9166: @example
 9167: IF
 9168:   @{ x @}
 9169: BEGIN
 9170:   \ x ? 
 9171: [ 1 cs-roll ] THEN
 9172:   ...
 9173: UNTIL
 9174: @end example
 9175: 
 9176: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9177: optimistically assumes that it lives until the @code{THEN}. It notices
 9178: this difference when it compiles the @code{UNTIL} and issues a
 9179: warning. The user can avoid the warning, and make sure that @code{x}
 9180: is not used in the wrong area by using explicit scoping:
 9181: @example
 9182: IF
 9183:   SCOPE
 9184:   @{ x @}
 9185:   ENDSCOPE
 9186: BEGIN
 9187: [ 1 cs-roll ] THEN
 9188:   ...
 9189: UNTIL
 9190: @end example
 9191: 
 9192: Since the guess is optimistic, there will be no spurious error messages
 9193: about undefined locals.
 9194: 
 9195: If the @code{BEGIN} is not reachable from above (e.g., after
 9196: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9197: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9198: defined later. Therefore, the compiler assumes that no locals are
 9199: visible after the @code{BEGIN}. However, the user can use
 9200: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9201: visible at the BEGIN as at the point where the top control-flow stack
 9202: item was created.
 9203: 
 9204: 
 9205: doc-assume-live
 9206: 
 9207: 
 9208: @noindent
 9209: E.g.,
 9210: @example
 9211: @{ x @}
 9212: AHEAD
 9213: ASSUME-LIVE
 9214: BEGIN
 9215:   x
 9216: [ 1 CS-ROLL ] THEN
 9217:   ...
 9218: UNTIL
 9219: @end example
 9220: 
 9221: Other cases where the locals are defined before the @code{BEGIN} can be
 9222: handled by inserting an appropriate @code{CS-ROLL} before the
 9223: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9224: behind the @code{ASSUME-LIVE}).
 9225: 
 9226: Cases where locals are defined after the @code{BEGIN} (but should be
 9227: visible immediately after the @code{BEGIN}) can only be handled by
 9228: rearranging the loop. E.g., the ``most insidious'' example above can be
 9229: arranged into:
 9230: @example
 9231: BEGIN
 9232:   @{ x @}
 9233:   ... 0=
 9234: WHILE
 9235:   x
 9236: REPEAT
 9237: @end example
 9238: 
 9239: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9240: @subsubsection How long do locals live?
 9241: @cindex locals lifetime
 9242: @cindex lifetime of locals
 9243: 
 9244: The right answer for the lifetime question would be: A local lives at
 9245: least as long as it can be accessed. For a value-flavoured local this
 9246: means: until the end of its visibility. However, a variable-flavoured
 9247: local could be accessed through its address far beyond its visibility
 9248: scope. Ultimately, this would mean that such locals would have to be
 9249: garbage collected. Since this entails un-Forth-like implementation
 9250: complexities, I adopted the same cowardly solution as some other
 9251: languages (e.g., C): The local lives only as long as it is visible;
 9252: afterwards its address is invalid (and programs that access it
 9253: afterwards are erroneous).
 9254: 
 9255: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9256: @subsubsection Locals programming style
 9257: @cindex locals programming style
 9258: @cindex programming style, locals
 9259: 
 9260: The freedom to define locals anywhere has the potential to change
 9261: programming styles dramatically. In particular, the need to use the
 9262: return stack for intermediate storage vanishes. Moreover, all stack
 9263: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9264: determined arguments) can be eliminated: If the stack items are in the
 9265: wrong order, just write a locals definition for all of them; then
 9266: write the items in the order you want.
 9267: 
 9268: This seems a little far-fetched and eliminating stack manipulations is
 9269: unlikely to become a conscious programming objective. Still, the number
 9270: of stack manipulations will be reduced dramatically if local variables
 9271: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9272: a traditional implementation of @code{max}).
 9273: 
 9274: This shows one potential benefit of locals: making Forth programs more
 9275: readable. Of course, this benefit will only be realized if the
 9276: programmers continue to honour the principle of factoring instead of
 9277: using the added latitude to make the words longer.
 9278: 
 9279: @cindex single-assignment style for locals
 9280: Using @code{TO} can and should be avoided.  Without @code{TO},
 9281: every value-flavoured local has only a single assignment and many
 9282: advantages of functional languages apply to Forth. I.e., programs are
 9283: easier to analyse, to optimize and to read: It is clear from the
 9284: definition what the local stands for, it does not turn into something
 9285: different later.
 9286: 
 9287: E.g., a definition using @code{TO} might look like this:
 9288: @example
 9289: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9290:  u1 u2 min 0
 9291:  ?do
 9292:    addr1 c@@ addr2 c@@ -
 9293:    ?dup-if
 9294:      unloop exit
 9295:    then
 9296:    addr1 char+ TO addr1
 9297:    addr2 char+ TO addr2
 9298:  loop
 9299:  u1 u2 - ;
 9300: @end example
 9301: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9302: every loop iteration. @code{strcmp} is a typical example of the
 9303: readability problems of using @code{TO}. When you start reading
 9304: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9305: string. Only near the end of the loop you realize that it is something
 9306: else.
 9307: 
 9308: This can be avoided by defining two locals at the start of the loop that
 9309: are initialized with the right value for the current iteration.
 9310: @example
 9311: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9312:  addr1 addr2
 9313:  u1 u2 min 0 
 9314:  ?do @{ s1 s2 @}
 9315:    s1 c@@ s2 c@@ -
 9316:    ?dup-if
 9317:      unloop exit
 9318:    then
 9319:    s1 char+ s2 char+
 9320:  loop
 9321:  2drop
 9322:  u1 u2 - ;
 9323: @end example
 9324: Here it is clear from the start that @code{s1} has a different value
 9325: in every loop iteration.
 9326: 
 9327: @node Locals implementation,  , Locals programming style, Gforth locals
 9328: @subsubsection Locals implementation
 9329: @cindex locals implementation
 9330: @cindex implementation of locals
 9331: 
 9332: @cindex locals stack
 9333: Gforth uses an extra locals stack. The most compelling reason for
 9334: this is that the return stack is not float-aligned; using an extra stack
 9335: also eliminates the problems and restrictions of using the return stack
 9336: as locals stack. Like the other stacks, the locals stack grows toward
 9337: lower addresses. A few primitives allow an efficient implementation:
 9338: 
 9339: 
 9340: doc-@local#
 9341: doc-f@local#
 9342: doc-laddr#
 9343: doc-lp+!#
 9344: doc-lp!
 9345: doc->l
 9346: doc-f>l
 9347: 
 9348: 
 9349: In addition to these primitives, some specializations of these
 9350: primitives for commonly occurring inline arguments are provided for
 9351: efficiency reasons, e.g., @code{@@local0} as specialization of
 9352: @code{@@local#} for the inline argument 0. The following compiling words
 9353: compile the right specialized version, or the general version, as
 9354: appropriate:
 9355: 
 9356: 
 9357: @c doc-compile-@local
 9358: @c doc-compile-f@local
 9359: doc-compile-lp+!
 9360: 
 9361: 
 9362: Combinations of conditional branches and @code{lp+!#} like
 9363: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9364: is taken) are provided for efficiency and correctness in loops.
 9365: 
 9366: A special area in the dictionary space is reserved for keeping the
 9367: local variable names. @code{@{} switches the dictionary pointer to this
 9368: area and @code{@}} switches it back and generates the locals
 9369: initializing code. @code{W:} etc.@ are normal defining words. This
 9370: special area is cleared at the start of every colon definition.
 9371: 
 9372: @cindex word list for defining locals
 9373: A special feature of Gforth's dictionary is used to implement the
 9374: definition of locals without type specifiers: every word list (aka
 9375: vocabulary) has its own methods for searching
 9376: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9377: with a special search method: When it is searched for a word, it
 9378: actually creates that word using @code{W:}. @code{@{} changes the search
 9379: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9380: and then the word list for defining locals without type specifiers.
 9381: 
 9382: The lifetime rules support a stack discipline within a colon
 9383: definition: The lifetime of a local is either nested with other locals
 9384: lifetimes or it does not overlap them.
 9385: 
 9386: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9387: pointer manipulation is generated. Between control structure words
 9388: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9389: is the simplest of the other three control flow words. It has to
 9390: restore the locals stack depth of the corresponding @code{BEGIN}
 9391: before branching. The code looks like this:
 9392: @format
 9393: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9394: @code{branch} <begin>
 9395: @end format
 9396: 
 9397: @code{UNTIL} is a little more complicated: If it branches back, it
 9398: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9399: the locals stack must not be changed. The compiler generates the
 9400: following code:
 9401: @format
 9402: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9403: @end format
 9404: The locals stack pointer is only adjusted if the branch is taken.
 9405: 
 9406: @code{THEN} can produce somewhat inefficient code:
 9407: @format
 9408: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9409: <orig target>:
 9410: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9411: @end format
 9412: The second @code{lp+!#} adjusts the locals stack pointer from the
 9413: level at the @i{orig} point to the level after the @code{THEN}. The
 9414: first @code{lp+!#} adjusts the locals stack pointer from the current
 9415: level to the level at the orig point, so the complete effect is an
 9416: adjustment from the current level to the right level after the
 9417: @code{THEN}.
 9418: 
 9419: @cindex locals information on the control-flow stack
 9420: @cindex control-flow stack items, locals information
 9421: In a conventional Forth implementation a dest control-flow stack entry
 9422: is just the target address and an orig entry is just the address to be
 9423: patched. Our locals implementation adds a word list to every orig or dest
 9424: item. It is the list of locals visible (or assumed visible) at the point
 9425: described by the entry. Our implementation also adds a tag to identify
 9426: the kind of entry, in particular to differentiate between live and dead
 9427: (reachable and unreachable) orig entries.
 9428: 
 9429: A few unusual operations have to be performed on locals word lists:
 9430: 
 9431: 
 9432: doc-common-list
 9433: doc-sub-list?
 9434: doc-list-size
 9435: 
 9436: 
 9437: Several features of our locals word list implementation make these
 9438: operations easy to implement: The locals word lists are organised as
 9439: linked lists; the tails of these lists are shared, if the lists
 9440: contain some of the same locals; and the address of a name is greater
 9441: than the address of the names behind it in the list.
 9442: 
 9443: Another important implementation detail is the variable
 9444: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9445: determine if they can be reached directly or only through the branch
 9446: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9447: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9448: definition, by @code{BEGIN} and usually by @code{THEN}.
 9449: 
 9450: Counted loops are similar to other loops in most respects, but
 9451: @code{LEAVE} requires special attention: It performs basically the same
 9452: service as @code{AHEAD}, but it does not create a control-flow stack
 9453: entry. Therefore the information has to be stored elsewhere;
 9454: traditionally, the information was stored in the target fields of the
 9455: branches created by the @code{LEAVE}s, by organizing these fields into a
 9456: linked list. Unfortunately, this clever trick does not provide enough
 9457: space for storing our extended control flow information. Therefore, we
 9458: introduce another stack, the leave stack. It contains the control-flow
 9459: stack entries for all unresolved @code{LEAVE}s.
 9460: 
 9461: Local names are kept until the end of the colon definition, even if
 9462: they are no longer visible in any control-flow path. In a few cases
 9463: this may lead to increased space needs for the locals name area, but
 9464: usually less than reclaiming this space would cost in code size.
 9465: 
 9466: 
 9467: @node ANS Forth locals,  , Gforth locals, Locals
 9468: @subsection ANS Forth locals
 9469: @cindex locals, ANS Forth style
 9470: 
 9471: The ANS Forth locals wordset does not define a syntax for locals, but
 9472: words that make it possible to define various syntaxes. One of the
 9473: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9474: wordset, i.e.:
 9475: 
 9476: @example
 9477: @{ local1 local2 ... -- comment @}
 9478: @end example
 9479: @noindent
 9480: or
 9481: @example
 9482: @{ local1 local2 ... @}
 9483: @end example
 9484: 
 9485: The order of the locals corresponds to the order in a stack comment. The
 9486: restrictions are:
 9487: 
 9488: @itemize @bullet
 9489: @item
 9490: Locals can only be cell-sized values (no type specifiers are allowed).
 9491: @item
 9492: Locals can be defined only outside control structures.
 9493: @item
 9494: Locals can interfere with explicit usage of the return stack. For the
 9495: exact (and long) rules, see the standard. If you don't use return stack
 9496: accessing words in a definition using locals, you will be all right. The
 9497: purpose of this rule is to make locals implementation on the return
 9498: stack easier.
 9499: @item
 9500: The whole definition must be in one line.
 9501: @end itemize
 9502: 
 9503: Locals defined in ANS Forth behave like @code{VALUE}s
 9504: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9505: name produces their value. Their value can be changed using @code{TO}.
 9506: 
 9507: Since the syntax above is supported by Gforth directly, you need not do
 9508: anything to use it. If you want to port a program using this syntax to
 9509: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9510: syntax on the other system.
 9511: 
 9512: Note that a syntax shown in the standard, section A.13 looks
 9513: similar, but is quite different in having the order of locals
 9514: reversed. Beware!
 9515: 
 9516: The ANS Forth locals wordset itself consists of one word:
 9517: 
 9518: doc-(local)
 9519: 
 9520: The ANS Forth locals extension wordset defines a syntax using
 9521: @code{locals|}, but it is so awful that we strongly recommend not to use
 9522: it. We have implemented this syntax to make porting to Gforth easy, but
 9523: do not document it here. The problem with this syntax is that the locals
 9524: are defined in an order reversed with respect to the standard stack
 9525: comment notation, making programs harder to read, and easier to misread
 9526: and miswrite. The only merit of this syntax is that it is easy to
 9527: implement using the ANS Forth locals wordset.
 9528: 
 9529: 
 9530: @c ----------------------------------------------------------
 9531: @node Structures, Object-oriented Forth, Locals, Words
 9532: @section  Structures
 9533: @cindex structures
 9534: @cindex records
 9535: 
 9536: This section presents the structure package that comes with Gforth. A
 9537: version of the package implemented in ANS Forth is available in
 9538: @file{compat/struct.fs}. This package was inspired by a posting on
 9539: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9540: possibly John Hayes). A version of this section has been published in
 9541: M. Anton Ertl,
 9542: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9543: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9544: 13--16. Marcel Hendrix provided helpful comments.
 9545: 
 9546: @menu
 9547: * Why explicit structure support?::  
 9548: * Structure Usage::             
 9549: * Structure Naming Convention::  
 9550: * Structure Implementation::    
 9551: * Structure Glossary::          
 9552: @end menu
 9553: 
 9554: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9555: @subsection Why explicit structure support?
 9556: 
 9557: @cindex address arithmetic for structures
 9558: @cindex structures using address arithmetic
 9559: If we want to use a structure containing several fields, we could simply
 9560: reserve memory for it, and access the fields using address arithmetic
 9561: (@pxref{Address arithmetic}). As an example, consider a structure with
 9562: the following fields
 9563: 
 9564: @table @code
 9565: @item a
 9566: is a float
 9567: @item b
 9568: is a cell
 9569: @item c
 9570: is a float
 9571: @end table
 9572: 
 9573: Given the (float-aligned) base address of the structure we get the
 9574: address of the field
 9575: 
 9576: @table @code
 9577: @item a
 9578: without doing anything further.
 9579: @item b
 9580: with @code{float+}
 9581: @item c
 9582: with @code{float+ cell+ faligned}
 9583: @end table
 9584: 
 9585: It is easy to see that this can become quite tiring. 
 9586: 
 9587: Moreover, it is not very readable, because seeing a
 9588: @code{cell+} tells us neither which kind of structure is
 9589: accessed nor what field is accessed; we have to somehow infer the kind
 9590: of structure, and then look up in the documentation, which field of
 9591: that structure corresponds to that offset.
 9592: 
 9593: Finally, this kind of address arithmetic also causes maintenance
 9594: troubles: If you add or delete a field somewhere in the middle of the
 9595: structure, you have to find and change all computations for the fields
 9596: afterwards.
 9597: 
 9598: So, instead of using @code{cell+} and friends directly, how
 9599: about storing the offsets in constants:
 9600: 
 9601: @example
 9602: 0 constant a-offset
 9603: 0 float+ constant b-offset
 9604: 0 float+ cell+ faligned c-offset
 9605: @end example
 9606: 
 9607: Now we can get the address of field @code{x} with @code{x-offset
 9608: +}. This is much better in all respects. Of course, you still
 9609: have to change all later offset definitions if you add a field. You can
 9610: fix this by declaring the offsets in the following way:
 9611: 
 9612: @example
 9613: 0 constant a-offset
 9614: a-offset float+ constant b-offset
 9615: b-offset cell+ faligned constant c-offset
 9616: @end example
 9617: 
 9618: Since we always use the offsets with @code{+}, we could use a defining
 9619: word @code{cfield} that includes the @code{+} in the action of the
 9620: defined word:
 9621: 
 9622: @example
 9623: : cfield ( n "name" -- )
 9624:     create ,
 9625: does> ( name execution: addr1 -- addr2 )
 9626:     @@ + ;
 9627: 
 9628: 0 cfield a
 9629: 0 a float+ cfield b
 9630: 0 b cell+ faligned cfield c
 9631: @end example
 9632: 
 9633: Instead of @code{x-offset +}, we now simply write @code{x}.
 9634: 
 9635: The structure field words now can be used quite nicely. However,
 9636: their definition is still a bit cumbersome: We have to repeat the
 9637: name, the information about size and alignment is distributed before
 9638: and after the field definitions etc.  The structure package presented
 9639: here addresses these problems.
 9640: 
 9641: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9642: @subsection Structure Usage
 9643: @cindex structure usage
 9644: 
 9645: @cindex @code{field} usage
 9646: @cindex @code{struct} usage
 9647: @cindex @code{end-struct} usage
 9648: You can define a structure for a (data-less) linked list with:
 9649: @example
 9650: struct
 9651:     cell% field list-next
 9652: end-struct list%
 9653: @end example
 9654: 
 9655: With the address of the list node on the stack, you can compute the
 9656: address of the field that contains the address of the next node with
 9657: @code{list-next}. E.g., you can determine the length of a list
 9658: with:
 9659: 
 9660: @example
 9661: : list-length ( list -- n )
 9662: \ "list" is a pointer to the first element of a linked list
 9663: \ "n" is the length of the list
 9664:     0 BEGIN ( list1 n1 )
 9665:         over
 9666:     WHILE ( list1 n1 )
 9667:         1+ swap list-next @@ swap
 9668:     REPEAT
 9669:     nip ;
 9670: @end example
 9671: 
 9672: You can reserve memory for a list node in the dictionary with
 9673: @code{list% %allot}, which leaves the address of the list node on the
 9674: stack. For the equivalent allocation on the heap you can use @code{list%
 9675: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9676: use @code{list% %allocate}). You can get the the size of a list
 9677: node with @code{list% %size} and its alignment with @code{list%
 9678: %alignment}.
 9679: 
 9680: Note that in ANS Forth the body of a @code{create}d word is
 9681: @code{aligned} but not necessarily @code{faligned};
 9682: therefore, if you do a:
 9683: 
 9684: @example
 9685: create @emph{name} foo% %allot drop
 9686: @end example
 9687: 
 9688: @noindent
 9689: then the memory alloted for @code{foo%} is guaranteed to start at the
 9690: body of @code{@emph{name}} only if @code{foo%} contains only character,
 9691: cell and double fields.  Therefore, if your structure contains floats,
 9692: better use
 9693: 
 9694: @example
 9695: foo% %allot constant @emph{name}
 9696: @end example
 9697: 
 9698: @cindex structures containing structures
 9699: You can include a structure @code{foo%} as a field of
 9700: another structure, like this:
 9701: @example
 9702: struct
 9703: ...
 9704:     foo% field ...
 9705: ...
 9706: end-struct ...
 9707: @end example
 9708: 
 9709: @cindex structure extension
 9710: @cindex extended records
 9711: Instead of starting with an empty structure, you can extend an
 9712: existing structure. E.g., a plain linked list without data, as defined
 9713: above, is hardly useful; You can extend it to a linked list of integers,
 9714: like this:@footnote{This feature is also known as @emph{extended
 9715: records}. It is the main innovation in the Oberon language; in other
 9716: words, adding this feature to Modula-2 led Wirth to create a new
 9717: language, write a new compiler etc.  Adding this feature to Forth just
 9718: required a few lines of code.}
 9719: 
 9720: @example
 9721: list%
 9722:     cell% field intlist-int
 9723: end-struct intlist%
 9724: @end example
 9725: 
 9726: @code{intlist%} is a structure with two fields:
 9727: @code{list-next} and @code{intlist-int}.
 9728: 
 9729: @cindex structures containing arrays
 9730: You can specify an array type containing @emph{n} elements of
 9731: type @code{foo%} like this:
 9732: 
 9733: @example
 9734: foo% @emph{n} *
 9735: @end example
 9736: 
 9737: You can use this array type in any place where you can use a normal
 9738: type, e.g., when defining a @code{field}, or with
 9739: @code{%allot}.
 9740: 
 9741: @cindex first field optimization
 9742: The first field is at the base address of a structure and the word for
 9743: this field (e.g., @code{list-next}) actually does not change the address
 9744: on the stack. You may be tempted to leave it away in the interest of
 9745: run-time and space efficiency. This is not necessary, because the
 9746: structure package optimizes this case: If you compile a first-field
 9747: words, no code is generated. So, in the interest of readability and
 9748: maintainability you should include the word for the field when accessing
 9749: the field.
 9750: 
 9751: 
 9752: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 9753: @subsection Structure Naming Convention
 9754: @cindex structure naming convention
 9755: 
 9756: The field names that come to (my) mind are often quite generic, and,
 9757: if used, would cause frequent name clashes. E.g., many structures
 9758: probably contain a @code{counter} field. The structure names
 9759: that come to (my) mind are often also the logical choice for the names
 9760: of words that create such a structure.
 9761: 
 9762: Therefore, I have adopted the following naming conventions: 
 9763: 
 9764: @itemize @bullet
 9765: @cindex field naming convention
 9766: @item
 9767: The names of fields are of the form
 9768: @code{@emph{struct}-@emph{field}}, where
 9769: @code{@emph{struct}} is the basic name of the structure, and
 9770: @code{@emph{field}} is the basic name of the field. You can
 9771: think of field words as converting the (address of the)
 9772: structure into the (address of the) field.
 9773: 
 9774: @cindex structure naming convention
 9775: @item
 9776: The names of structures are of the form
 9777: @code{@emph{struct}%}, where
 9778: @code{@emph{struct}} is the basic name of the structure.
 9779: @end itemize
 9780: 
 9781: This naming convention does not work that well for fields of extended
 9782: structures; e.g., the integer list structure has a field
 9783: @code{intlist-int}, but has @code{list-next}, not
 9784: @code{intlist-next}.
 9785: 
 9786: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 9787: @subsection Structure Implementation
 9788: @cindex structure implementation
 9789: @cindex implementation of structures
 9790: 
 9791: The central idea in the implementation is to pass the data about the
 9792: structure being built on the stack, not in some global
 9793: variable. Everything else falls into place naturally once this design
 9794: decision is made.
 9795: 
 9796: The type description on the stack is of the form @emph{align
 9797: size}. Keeping the size on the top-of-stack makes dealing with arrays
 9798: very simple.
 9799: 
 9800: @code{field} is a defining word that uses @code{Create}
 9801: and @code{DOES>}. The body of the field contains the offset
 9802: of the field, and the normal @code{DOES>} action is simply:
 9803: 
 9804: @example
 9805: @@ +
 9806: @end example
 9807: 
 9808: @noindent
 9809: i.e., add the offset to the address, giving the stack effect
 9810: @i{addr1 -- addr2} for a field.
 9811: 
 9812: @cindex first field optimization, implementation
 9813: This simple structure is slightly complicated by the optimization
 9814: for fields with offset 0, which requires a different
 9815: @code{DOES>}-part (because we cannot rely on there being
 9816: something on the stack if such a field is invoked during
 9817: compilation). Therefore, we put the different @code{DOES>}-parts
 9818: in separate words, and decide which one to invoke based on the
 9819: offset. For a zero offset, the field is basically a noop; it is
 9820: immediate, and therefore no code is generated when it is compiled.
 9821: 
 9822: @node Structure Glossary,  , Structure Implementation, Structures
 9823: @subsection Structure Glossary
 9824: @cindex structure glossary
 9825: 
 9826: 
 9827: doc-%align
 9828: doc-%alignment
 9829: doc-%alloc
 9830: doc-%allocate
 9831: doc-%allot
 9832: doc-cell%
 9833: doc-char%
 9834: doc-dfloat%
 9835: doc-double%
 9836: doc-end-struct
 9837: doc-field
 9838: doc-float%
 9839: doc-naligned
 9840: doc-sfloat%
 9841: doc-%size
 9842: doc-struct
 9843: 
 9844: 
 9845: @c -------------------------------------------------------------
 9846: @node Object-oriented Forth, Programming Tools, Structures, Words
 9847: @section Object-oriented Forth
 9848: 
 9849: Gforth comes with three packages for object-oriented programming:
 9850: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 9851: is preloaded, so you have to @code{include} them before use. The most
 9852: important differences between these packages (and others) are discussed
 9853: in @ref{Comparison with other object models}. All packages are written
 9854: in ANS Forth and can be used with any other ANS Forth.
 9855: 
 9856: @menu
 9857: * Why object-oriented programming?::  
 9858: * Object-Oriented Terminology::  
 9859: * Objects::                     
 9860: * OOF::                         
 9861: * Mini-OOF::                    
 9862: * Comparison with other object models::  
 9863: @end menu
 9864: 
 9865: @c ----------------------------------------------------------------
 9866: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
 9867: @subsection Why object-oriented programming?
 9868: @cindex object-oriented programming motivation
 9869: @cindex motivation for object-oriented programming
 9870: 
 9871: Often we have to deal with several data structures (@emph{objects}),
 9872: that have to be treated similarly in some respects, but differently in
 9873: others. Graphical objects are the textbook example: circles, triangles,
 9874: dinosaurs, icons, and others, and we may want to add more during program
 9875: development. We want to apply some operations to any graphical object,
 9876: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
 9877: has to do something different for every kind of object.
 9878: @comment TODO add some other operations eg perimeter, area
 9879: @comment and tie in to concrete examples later..
 9880: 
 9881: We could implement @code{draw} as a big @code{CASE}
 9882: control structure that executes the appropriate code depending on the
 9883: kind of object to be drawn. This would be not be very elegant, and,
 9884: moreover, we would have to change @code{draw} every time we add
 9885: a new kind of graphical object (say, a spaceship).
 9886: 
 9887: What we would rather do is: When defining spaceships, we would tell
 9888: the system: ``Here's how you @code{draw} a spaceship; you figure
 9889: out the rest''.
 9890: 
 9891: This is the problem that all systems solve that (rightfully) call
 9892: themselves object-oriented; the object-oriented packages presented here
 9893: solve this problem (and not much else).
 9894: @comment TODO ?list properties of oo systems.. oo vs o-based?
 9895: 
 9896: @c ------------------------------------------------------------------------
 9897: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
 9898: @subsection Object-Oriented Terminology
 9899: @cindex object-oriented terminology
 9900: @cindex terminology for object-oriented programming
 9901: 
 9902: This section is mainly for reference, so you don't have to understand
 9903: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 9904: short:
 9905: 
 9906: @table @emph
 9907: @cindex class
 9908: @item class
 9909: a data structure definition with some extras.
 9910: 
 9911: @cindex object
 9912: @item object
 9913: an instance of the data structure described by the class definition.
 9914: 
 9915: @cindex instance variables
 9916: @item instance variables
 9917: fields of the data structure.
 9918: 
 9919: @cindex selector
 9920: @cindex method selector
 9921: @cindex virtual function
 9922: @item selector
 9923: (or @emph{method selector}) a word (e.g.,
 9924: @code{draw}) that performs an operation on a variety of data
 9925: structures (classes). A selector describes @emph{what} operation to
 9926: perform. In C++ terminology: a (pure) virtual function.
 9927: 
 9928: @cindex method
 9929: @item method
 9930: the concrete definition that performs the operation
 9931: described by the selector for a specific class. A method specifies
 9932: @emph{how} the operation is performed for a specific class.
 9933: 
 9934: @cindex selector invocation
 9935: @cindex message send
 9936: @cindex invoking a selector
 9937: @item selector invocation
 9938: a call of a selector. One argument of the call (the TOS (top-of-stack))
 9939: is used for determining which method is used. In Smalltalk terminology:
 9940: a message (consisting of the selector and the other arguments) is sent
 9941: to the object.
 9942: 
 9943: @cindex receiving object
 9944: @item receiving object
 9945: the object used for determining the method executed by a selector
 9946: invocation. In the @file{objects.fs} model, it is the object that is on
 9947: the TOS when the selector is invoked. (@emph{Receiving} comes from
 9948: the Smalltalk @emph{message} terminology.)
 9949: 
 9950: @cindex child class
 9951: @cindex parent class
 9952: @cindex inheritance
 9953: @item child class
 9954: a class that has (@emph{inherits}) all properties (instance variables,
 9955: selectors, methods) from a @emph{parent class}. In Smalltalk
 9956: terminology: The subclass inherits from the superclass. In C++
 9957: terminology: The derived class inherits from the base class.
 9958: 
 9959: @end table
 9960: 
 9961: @c If you wonder about the message sending terminology, it comes from
 9962: @c a time when each object had it's own task and objects communicated via
 9963: @c message passing; eventually the Smalltalk developers realized that
 9964: @c they can do most things through simple (indirect) calls. They kept the
 9965: @c terminology.
 9966: 
 9967: @c --------------------------------------------------------------
 9968: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
 9969: @subsection The @file{objects.fs} model
 9970: @cindex objects
 9971: @cindex object-oriented programming
 9972: 
 9973: @cindex @file{objects.fs}
 9974: @cindex @file{oof.fs}
 9975: 
 9976: This section describes the @file{objects.fs} package. This material also
 9977: has been published in M. Anton Ertl,
 9978: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
 9979: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
 9980: 37--43.
 9981: @c McKewan's and Zsoter's packages
 9982: 
 9983: This section assumes that you have read @ref{Structures}.
 9984: 
 9985: The techniques on which this model is based have been used to implement
 9986: the parser generator, Gray, and have also been used in Gforth for
 9987: implementing the various flavours of word lists (hashed or not,
 9988: case-sensitive or not, special-purpose word lists for locals etc.).
 9989: 
 9990: 
 9991: @menu
 9992: * Properties of the Objects model::  
 9993: * Basic Objects Usage::         
 9994: * The Objects base class::      
 9995: * Creating objects::            
 9996: * Object-Oriented Programming Style::  
 9997: * Class Binding::               
 9998: * Method conveniences::         
 9999: * Classes and Scoping::         
10000: * Dividing classes::            
10001: * Object Interfaces::           
10002: * Objects Implementation::      
10003: * Objects Glossary::            
10004: @end menu
10005: 
10006: Marcel Hendrix provided helpful comments on this section.
10007: 
10008: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10009: @subsubsection Properties of the @file{objects.fs} model
10010: @cindex @file{objects.fs} properties
10011: 
10012: @itemize @bullet
10013: @item
10014: It is straightforward to pass objects on the stack. Passing
10015: selectors on the stack is a little less convenient, but possible.
10016: 
10017: @item
10018: Objects are just data structures in memory, and are referenced by their
10019: address. You can create words for objects with normal defining words
10020: like @code{constant}. Likewise, there is no difference between instance
10021: variables that contain objects and those that contain other data.
10022: 
10023: @item
10024: Late binding is efficient and easy to use.
10025: 
10026: @item
10027: It avoids parsing, and thus avoids problems with state-smartness
10028: and reduced extensibility; for convenience there are a few parsing
10029: words, but they have non-parsing counterparts. There are also a few
10030: defining words that parse. This is hard to avoid, because all standard
10031: defining words parse (except @code{:noname}); however, such
10032: words are not as bad as many other parsing words, because they are not
10033: state-smart.
10034: 
10035: @item
10036: It does not try to incorporate everything. It does a few things and does
10037: them well (IMO). In particular, this model was not designed to support
10038: information hiding (although it has features that may help); you can use
10039: a separate package for achieving this.
10040: 
10041: @item
10042: It is layered; you don't have to learn and use all features to use this
10043: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10044: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10045: are optional and independent of each other.
10046: 
10047: @item
10048: An implementation in ANS Forth is available.
10049: 
10050: @end itemize
10051: 
10052: 
10053: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10054: @subsubsection Basic @file{objects.fs} Usage
10055: @cindex basic objects usage
10056: @cindex objects, basic usage
10057: 
10058: You can define a class for graphical objects like this:
10059: 
10060: @cindex @code{class} usage
10061: @cindex @code{end-class} usage
10062: @cindex @code{selector} usage
10063: @example
10064: object class \ "object" is the parent class
10065:   selector draw ( x y graphical -- )
10066: end-class graphical
10067: @end example
10068: 
10069: This code defines a class @code{graphical} with an
10070: operation @code{draw}.  We can perform the operation
10071: @code{draw} on any @code{graphical} object, e.g.:
10072: 
10073: @example
10074: 100 100 t-rex draw
10075: @end example
10076: 
10077: @noindent
10078: where @code{t-rex} is a word (say, a constant) that produces a
10079: graphical object.
10080: 
10081: @comment TODO add a 2nd operation eg perimeter.. and use for
10082: @comment a concrete example
10083: 
10084: @cindex abstract class
10085: How do we create a graphical object? With the present definitions,
10086: we cannot create a useful graphical object. The class
10087: @code{graphical} describes graphical objects in general, but not
10088: any concrete graphical object type (C++ users would call it an
10089: @emph{abstract class}); e.g., there is no method for the selector
10090: @code{draw} in the class @code{graphical}.
10091: 
10092: For concrete graphical objects, we define child classes of the
10093: class @code{graphical}, e.g.:
10094: 
10095: @cindex @code{overrides} usage
10096: @cindex @code{field} usage in class definition
10097: @example
10098: graphical class \ "graphical" is the parent class
10099:   cell% field circle-radius
10100: 
10101: :noname ( x y circle -- )
10102:   circle-radius @@ draw-circle ;
10103: overrides draw
10104: 
10105: :noname ( n-radius circle -- )
10106:   circle-radius ! ;
10107: overrides construct
10108: 
10109: end-class circle
10110: @end example
10111: 
10112: Here we define a class @code{circle} as a child of @code{graphical},
10113: with field @code{circle-radius} (which behaves just like a field
10114: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10115: for the selectors @code{draw} and @code{construct} (@code{construct} is
10116: defined in @code{object}, the parent class of @code{graphical}).
10117: 
10118: Now we can create a circle on the heap (i.e.,
10119: @code{allocate}d memory) with:
10120: 
10121: @cindex @code{heap-new} usage
10122: @example
10123: 50 circle heap-new constant my-circle
10124: @end example
10125: 
10126: @noindent
10127: @code{heap-new} invokes @code{construct}, thus
10128: initializing the field @code{circle-radius} with 50. We can draw
10129: this new circle at (100,100) with:
10130: 
10131: @example
10132: 100 100 my-circle draw
10133: @end example
10134: 
10135: @cindex selector invocation, restrictions
10136: @cindex class definition, restrictions
10137: Note: You can only invoke a selector if the object on the TOS
10138: (the receiving object) belongs to the class where the selector was
10139: defined or one of its descendents; e.g., you can invoke
10140: @code{draw} only for objects belonging to @code{graphical}
10141: or its descendents (e.g., @code{circle}).  Immediately before
10142: @code{end-class}, the search order has to be the same as
10143: immediately after @code{class}.
10144: 
10145: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10146: @subsubsection The @file{object.fs} base class
10147: @cindex @code{object} class
10148: 
10149: When you define a class, you have to specify a parent class.  So how do
10150: you start defining classes? There is one class available from the start:
10151: @code{object}. It is ancestor for all classes and so is the
10152: only class that has no parent. It has two selectors: @code{construct}
10153: and @code{print}.
10154: 
10155: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10156: @subsubsection Creating objects
10157: @cindex creating objects
10158: @cindex object creation
10159: @cindex object allocation options
10160: 
10161: @cindex @code{heap-new} discussion
10162: @cindex @code{dict-new} discussion
10163: @cindex @code{construct} discussion
10164: You can create and initialize an object of a class on the heap with
10165: @code{heap-new} ( ... class -- object ) and in the dictionary
10166: (allocation with @code{allot}) with @code{dict-new} (
10167: ... class -- object ). Both words invoke @code{construct}, which
10168: consumes the stack items indicated by "..." above.
10169: 
10170: @cindex @code{init-object} discussion
10171: @cindex @code{class-inst-size} discussion
10172: If you want to allocate memory for an object yourself, you can get its
10173: alignment and size with @code{class-inst-size 2@@} ( class --
10174: align size ). Once you have memory for an object, you can initialize
10175: it with @code{init-object} ( ... class object -- );
10176: @code{construct} does only a part of the necessary work.
10177: 
10178: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10179: @subsubsection Object-Oriented Programming Style
10180: @cindex object-oriented programming style
10181: @cindex programming style, object-oriented
10182: 
10183: This section is not exhaustive.
10184: 
10185: @cindex stack effects of selectors
10186: @cindex selectors and stack effects
10187: In general, it is a good idea to ensure that all methods for the
10188: same selector have the same stack effect: when you invoke a selector,
10189: you often have no idea which method will be invoked, so, unless all
10190: methods have the same stack effect, you will not know the stack effect
10191: of the selector invocation.
10192: 
10193: One exception to this rule is methods for the selector
10194: @code{construct}. We know which method is invoked, because we
10195: specify the class to be constructed at the same place. Actually, I
10196: defined @code{construct} as a selector only to give the users a
10197: convenient way to specify initialization. The way it is used, a
10198: mechanism different from selector invocation would be more natural
10199: (but probably would take more code and more space to explain).
10200: 
10201: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10202: @subsubsection Class Binding
10203: @cindex class binding
10204: @cindex early binding
10205: 
10206: @cindex late binding
10207: Normal selector invocations determine the method at run-time depending
10208: on the class of the receiving object. This run-time selection is called
10209: @i{late binding}.
10210: 
10211: Sometimes it's preferable to invoke a different method. For example,
10212: you might want to use the simple method for @code{print}ing
10213: @code{object}s instead of the possibly long-winded @code{print} method
10214: of the receiver class. You can achieve this by replacing the invocation
10215: of @code{print} with:
10216: 
10217: @cindex @code{[bind]} usage
10218: @example
10219: [bind] object print
10220: @end example
10221: 
10222: @noindent
10223: in compiled code or:
10224: 
10225: @cindex @code{bind} usage
10226: @example
10227: bind object print
10228: @end example
10229: 
10230: @cindex class binding, alternative to
10231: @noindent
10232: in interpreted code. Alternatively, you can define the method with a
10233: name (e.g., @code{print-object}), and then invoke it through the
10234: name. Class binding is just a (often more convenient) way to achieve
10235: the same effect; it avoids name clutter and allows you to invoke
10236: methods directly without naming them first.
10237: 
10238: @cindex superclass binding
10239: @cindex parent class binding
10240: A frequent use of class binding is this: When we define a method
10241: for a selector, we often want the method to do what the selector does
10242: in the parent class, and a little more. There is a special word for
10243: this purpose: @code{[parent]}; @code{[parent]
10244: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10245: selector}}, where @code{@emph{parent}} is the parent
10246: class of the current class. E.g., a method definition might look like:
10247: 
10248: @cindex @code{[parent]} usage
10249: @example
10250: :noname
10251:   dup [parent] foo \ do parent's foo on the receiving object
10252:   ... \ do some more
10253: ; overrides foo
10254: @end example
10255: 
10256: @cindex class binding as optimization
10257: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10258: March 1997), Andrew McKewan presents class binding as an optimization
10259: technique. I recommend not using it for this purpose unless you are in
10260: an emergency. Late binding is pretty fast with this model anyway, so the
10261: benefit of using class binding is small; the cost of using class binding
10262: where it is not appropriate is reduced maintainability.
10263: 
10264: While we are at programming style questions: You should bind
10265: selectors only to ancestor classes of the receiving object. E.g., say,
10266: you know that the receiving object is of class @code{foo} or its
10267: descendents; then you should bind only to @code{foo} and its
10268: ancestors.
10269: 
10270: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10271: @subsubsection Method conveniences
10272: @cindex method conveniences
10273: 
10274: In a method you usually access the receiving object pretty often.  If
10275: you define the method as a plain colon definition (e.g., with
10276: @code{:noname}), you may have to do a lot of stack
10277: gymnastics. To avoid this, you can define the method with @code{m:
10278: ... ;m}. E.g., you could define the method for
10279: @code{draw}ing a @code{circle} with
10280: 
10281: @cindex @code{this} usage
10282: @cindex @code{m:} usage
10283: @cindex @code{;m} usage
10284: @example
10285: m: ( x y circle -- )
10286:   ( x y ) this circle-radius @@ draw-circle ;m
10287: @end example
10288: 
10289: @cindex @code{exit} in @code{m: ... ;m}
10290: @cindex @code{exitm} discussion
10291: @cindex @code{catch} in @code{m: ... ;m}
10292: When this method is executed, the receiver object is removed from the
10293: stack; you can access it with @code{this} (admittedly, in this
10294: example the use of @code{m: ... ;m} offers no advantage). Note
10295: that I specify the stack effect for the whole method (i.e. including
10296: the receiver object), not just for the code between @code{m:}
10297: and @code{;m}. You cannot use @code{exit} in
10298: @code{m:...;m}; instead, use
10299: @code{exitm}.@footnote{Moreover, for any word that calls
10300: @code{catch} and was defined before loading
10301: @code{objects.fs}, you have to redefine it like I redefined
10302: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10303: 
10304: @cindex @code{inst-var} usage
10305: You will frequently use sequences of the form @code{this
10306: @emph{field}} (in the example above: @code{this
10307: circle-radius}). If you use the field only in this way, you can
10308: define it with @code{inst-var} and eliminate the
10309: @code{this} before the field name. E.g., the @code{circle}
10310: class above could also be defined with:
10311: 
10312: @example
10313: graphical class
10314:   cell% inst-var radius
10315: 
10316: m: ( x y circle -- )
10317:   radius @@ draw-circle ;m
10318: overrides draw
10319: 
10320: m: ( n-radius circle -- )
10321:   radius ! ;m
10322: overrides construct
10323: 
10324: end-class circle
10325: @end example
10326: 
10327: @code{radius} can only be used in @code{circle} and its
10328: descendent classes and inside @code{m:...;m}.
10329: 
10330: @cindex @code{inst-value} usage
10331: You can also define fields with @code{inst-value}, which is
10332: to @code{inst-var} what @code{value} is to
10333: @code{variable}.  You can change the value of such a field with
10334: @code{[to-inst]}.  E.g., we could also define the class
10335: @code{circle} like this:
10336: 
10337: @example
10338: graphical class
10339:   inst-value radius
10340: 
10341: m: ( x y circle -- )
10342:   radius draw-circle ;m
10343: overrides draw
10344: 
10345: m: ( n-radius circle -- )
10346:   [to-inst] radius ;m
10347: overrides construct
10348: 
10349: end-class circle
10350: @end example
10351: 
10352: @c !! :m is easy to confuse with m:.  Another name would be better.
10353: 
10354: @c Finally, you can define named methods with @code{:m}.  One use of this
10355: @c feature is the definition of words that occur only in one class and are
10356: @c not intended to be overridden, but which still need method context
10357: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10358: @c would be bound frequently, if defined anonymously.
10359: 
10360: 
10361: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10362: @subsubsection Classes and Scoping
10363: @cindex classes and scoping
10364: @cindex scoping and classes
10365: 
10366: Inheritance is frequent, unlike structure extension. This exacerbates
10367: the problem with the field name convention (@pxref{Structure Naming
10368: Convention}): One always has to remember in which class the field was
10369: originally defined; changing a part of the class structure would require
10370: changes for renaming in otherwise unaffected code.
10371: 
10372: @cindex @code{inst-var} visibility
10373: @cindex @code{inst-value} visibility
10374: To solve this problem, I added a scoping mechanism (which was not in my
10375: original charter): A field defined with @code{inst-var} (or
10376: @code{inst-value}) is visible only in the class where it is defined and in
10377: the descendent classes of this class.  Using such fields only makes
10378: sense in @code{m:}-defined methods in these classes anyway.
10379: 
10380: This scoping mechanism allows us to use the unadorned field name,
10381: because name clashes with unrelated words become much less likely.
10382: 
10383: @cindex @code{protected} discussion
10384: @cindex @code{private} discussion
10385: Once we have this mechanism, we can also use it for controlling the
10386: visibility of other words: All words defined after
10387: @code{protected} are visible only in the current class and its
10388: descendents. @code{public} restores the compilation
10389: (i.e. @code{current}) word list that was in effect before. If you
10390: have several @code{protected}s without an intervening
10391: @code{public} or @code{set-current}, @code{public}
10392: will restore the compilation word list in effect before the first of
10393: these @code{protected}s.
10394: 
10395: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10396: @subsubsection Dividing classes
10397: @cindex Dividing classes
10398: @cindex @code{methods}...@code{end-methods}
10399: 
10400: You may want to do the definition of methods separate from the
10401: definition of the class, its selectors, fields, and instance variables,
10402: i.e., separate the implementation from the definition.  You can do this
10403: in the following way:
10404: 
10405: @example
10406: graphical class
10407:   inst-value radius
10408: end-class circle
10409: 
10410: ... \ do some other stuff
10411: 
10412: circle methods \ now we are ready
10413: 
10414: m: ( x y circle -- )
10415:   radius draw-circle ;m
10416: overrides draw
10417: 
10418: m: ( n-radius circle -- )
10419:   [to-inst] radius ;m
10420: overrides construct
10421: 
10422: end-methods
10423: @end example
10424: 
10425: You can use several @code{methods}...@code{end-methods} sections.  The
10426: only things you can do to the class in these sections are: defining
10427: methods, and overriding the class's selectors.  You must not define new
10428: selectors or fields.
10429: 
10430: Note that you often have to override a selector before using it.  In
10431: particular, you usually have to override @code{construct} with a new
10432: method before you can invoke @code{heap-new} and friends.  E.g., you
10433: must not create a circle before the @code{overrides construct} sequence
10434: in the example above.
10435: 
10436: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10437: @subsubsection Object Interfaces
10438: @cindex object interfaces
10439: @cindex interfaces for objects
10440: 
10441: In this model you can only call selectors defined in the class of the
10442: receiving objects or in one of its ancestors. If you call a selector
10443: with a receiving object that is not in one of these classes, the
10444: result is undefined; if you are lucky, the program crashes
10445: immediately.
10446: 
10447: @cindex selectors common to hardly-related classes
10448: Now consider the case when you want to have a selector (or several)
10449: available in two classes: You would have to add the selector to a
10450: common ancestor class, in the worst case to @code{object}. You
10451: may not want to do this, e.g., because someone else is responsible for
10452: this ancestor class.
10453: 
10454: The solution for this problem is interfaces. An interface is a
10455: collection of selectors. If a class implements an interface, the
10456: selectors become available to the class and its descendents. A class
10457: can implement an unlimited number of interfaces. For the problem
10458: discussed above, we would define an interface for the selector(s), and
10459: both classes would implement the interface.
10460: 
10461: As an example, consider an interface @code{storage} for
10462: writing objects to disk and getting them back, and a class
10463: @code{foo} that implements it. The code would look like this:
10464: 
10465: @cindex @code{interface} usage
10466: @cindex @code{end-interface} usage
10467: @cindex @code{implementation} usage
10468: @example
10469: interface
10470:   selector write ( file object -- )
10471:   selector read1 ( file object -- )
10472: end-interface storage
10473: 
10474: bar class
10475:   storage implementation
10476: 
10477: ... overrides write
10478: ... overrides read1
10479: ...
10480: end-class foo
10481: @end example
10482: 
10483: @noindent
10484: (I would add a word @code{read} @i{( file -- object )} that uses
10485: @code{read1} internally, but that's beyond the point illustrated
10486: here.)
10487: 
10488: Note that you cannot use @code{protected} in an interface; and
10489: of course you cannot define fields.
10490: 
10491: In the Neon model, all selectors are available for all classes;
10492: therefore it does not need interfaces. The price you pay in this model
10493: is slower late binding, and therefore, added complexity to avoid late
10494: binding.
10495: 
10496: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10497: @subsubsection @file{objects.fs} Implementation
10498: @cindex @file{objects.fs} implementation
10499: 
10500: @cindex @code{object-map} discussion
10501: An object is a piece of memory, like one of the data structures
10502: described with @code{struct...end-struct}. It has a field
10503: @code{object-map} that points to the method map for the object's
10504: class.
10505: 
10506: @cindex method map
10507: @cindex virtual function table
10508: The @emph{method map}@footnote{This is Self terminology; in C++
10509: terminology: virtual function table.} is an array that contains the
10510: execution tokens (@i{xt}s) of the methods for the object's class. Each
10511: selector contains an offset into a method map.
10512: 
10513: @cindex @code{selector} implementation, class
10514: @code{selector} is a defining word that uses
10515: @code{CREATE} and @code{DOES>}. The body of the
10516: selector contains the offset; the @code{DOES>} action for a
10517: class selector is, basically:
10518: 
10519: @example
10520: ( object addr ) @@ over object-map @@ + @@ execute
10521: @end example
10522: 
10523: Since @code{object-map} is the first field of the object, it
10524: does not generate any code. As you can see, calling a selector has a
10525: small, constant cost.
10526: 
10527: @cindex @code{current-interface} discussion
10528: @cindex class implementation and representation
10529: A class is basically a @code{struct} combined with a method
10530: map. During the class definition the alignment and size of the class
10531: are passed on the stack, just as with @code{struct}s, so
10532: @code{field} can also be used for defining class
10533: fields. However, passing more items on the stack would be
10534: inconvenient, so @code{class} builds a data structure in memory,
10535: which is accessed through the variable
10536: @code{current-interface}. After its definition is complete, the
10537: class is represented on the stack by a pointer (e.g., as parameter for
10538: a child class definition).
10539: 
10540: A new class starts off with the alignment and size of its parent,
10541: and a copy of the parent's method map. Defining new fields extends the
10542: size and alignment; likewise, defining new selectors extends the
10543: method map. @code{overrides} just stores a new @i{xt} in the method
10544: map at the offset given by the selector.
10545: 
10546: @cindex class binding, implementation
10547: Class binding just gets the @i{xt} at the offset given by the selector
10548: from the class's method map and @code{compile,}s (in the case of
10549: @code{[bind]}) it.
10550: 
10551: @cindex @code{this} implementation
10552: @cindex @code{catch} and @code{this}
10553: @cindex @code{this} and @code{catch}
10554: I implemented @code{this} as a @code{value}. At the
10555: start of an @code{m:...;m} method the old @code{this} is
10556: stored to the return stack and restored at the end; and the object on
10557: the TOS is stored @code{TO this}. This technique has one
10558: disadvantage: If the user does not leave the method via
10559: @code{;m}, but via @code{throw} or @code{exit},
10560: @code{this} is not restored (and @code{exit} may
10561: crash). To deal with the @code{throw} problem, I have redefined
10562: @code{catch} to save and restore @code{this}; the same
10563: should be done with any word that can catch an exception. As for
10564: @code{exit}, I simply forbid it (as a replacement, there is
10565: @code{exitm}).
10566: 
10567: @cindex @code{inst-var} implementation
10568: @code{inst-var} is just the same as @code{field}, with
10569: a different @code{DOES>} action:
10570: @example
10571: @@ this +
10572: @end example
10573: Similar for @code{inst-value}.
10574: 
10575: @cindex class scoping implementation
10576: Each class also has a word list that contains the words defined with
10577: @code{inst-var} and @code{inst-value}, and its protected
10578: words. It also has a pointer to its parent. @code{class} pushes
10579: the word lists of the class and all its ancestors onto the search order stack,
10580: and @code{end-class} drops them.
10581: 
10582: @cindex interface implementation
10583: An interface is like a class without fields, parent and protected
10584: words; i.e., it just has a method map. If a class implements an
10585: interface, its method map contains a pointer to the method map of the
10586: interface. The positive offsets in the map are reserved for class
10587: methods, therefore interface map pointers have negative
10588: offsets. Interfaces have offsets that are unique throughout the
10589: system, unlike class selectors, whose offsets are only unique for the
10590: classes where the selector is available (invokable).
10591: 
10592: This structure means that interface selectors have to perform one
10593: indirection more than class selectors to find their method. Their body
10594: contains the interface map pointer offset in the class method map, and
10595: the method offset in the interface method map. The
10596: @code{does>} action for an interface selector is, basically:
10597: 
10598: @example
10599: ( object selector-body )
10600: 2dup selector-interface @@ ( object selector-body object interface-offset )
10601: swap object-map @@ + @@ ( object selector-body map )
10602: swap selector-offset @@ + @@ execute
10603: @end example
10604: 
10605: where @code{object-map} and @code{selector-offset} are
10606: first fields and generate no code.
10607: 
10608: As a concrete example, consider the following code:
10609: 
10610: @example
10611: interface
10612:   selector if1sel1
10613:   selector if1sel2
10614: end-interface if1
10615: 
10616: object class
10617:   if1 implementation
10618:   selector cl1sel1
10619:   cell% inst-var cl1iv1
10620: 
10621: ' m1 overrides construct
10622: ' m2 overrides if1sel1
10623: ' m3 overrides if1sel2
10624: ' m4 overrides cl1sel2
10625: end-class cl1
10626: 
10627: create obj1 object dict-new drop
10628: create obj2 cl1    dict-new drop
10629: @end example
10630: 
10631: The data structure created by this code (including the data structure
10632: for @code{object}) is shown in the
10633: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10634: @comment TODO add this diagram..
10635: 
10636: @node Objects Glossary,  , Objects Implementation, Objects
10637: @subsubsection @file{objects.fs} Glossary
10638: @cindex @file{objects.fs} Glossary
10639: 
10640: 
10641: doc---objects-bind
10642: doc---objects-<bind>
10643: doc---objects-bind'
10644: doc---objects-[bind]
10645: doc---objects-class
10646: doc---objects-class->map
10647: doc---objects-class-inst-size
10648: doc---objects-class-override!
10649: doc---objects-class-previous
10650: doc---objects-class>order
10651: doc---objects-construct
10652: doc---objects-current'
10653: doc---objects-[current]
10654: doc---objects-current-interface
10655: doc---objects-dict-new
10656: doc---objects-end-class
10657: doc---objects-end-class-noname
10658: doc---objects-end-interface
10659: doc---objects-end-interface-noname
10660: doc---objects-end-methods
10661: doc---objects-exitm
10662: doc---objects-heap-new
10663: doc---objects-implementation
10664: doc---objects-init-object
10665: doc---objects-inst-value
10666: doc---objects-inst-var
10667: doc---objects-interface
10668: doc---objects-m:
10669: doc---objects-:m
10670: doc---objects-;m
10671: doc---objects-method
10672: doc---objects-methods
10673: doc---objects-object
10674: doc---objects-overrides
10675: doc---objects-[parent]
10676: doc---objects-print
10677: doc---objects-protected
10678: doc---objects-public
10679: doc---objects-selector
10680: doc---objects-this
10681: doc---objects-<to-inst>
10682: doc---objects-[to-inst]
10683: doc---objects-to-this
10684: doc---objects-xt-new
10685: 
10686: 
10687: @c -------------------------------------------------------------
10688: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10689: @subsection The @file{oof.fs} model
10690: @cindex oof
10691: @cindex object-oriented programming
10692: 
10693: @cindex @file{objects.fs}
10694: @cindex @file{oof.fs}
10695: 
10696: This section describes the @file{oof.fs} package.
10697: 
10698: The package described in this section has been used in bigFORTH since 1991, and
10699: used for two large applications: a chromatographic system used to
10700: create new medicaments, and a graphic user interface library (MINOS).
10701: 
10702: You can find a description (in German) of @file{oof.fs} in @cite{Object
10703: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10704: 10(2), 1994.
10705: 
10706: @menu
10707: * Properties of the OOF model::  
10708: * Basic OOF Usage::             
10709: * The OOF base class::          
10710: * Class Declaration::           
10711: * Class Implementation::        
10712: @end menu
10713: 
10714: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10715: @subsubsection Properties of the @file{oof.fs} model
10716: @cindex @file{oof.fs} properties
10717: 
10718: @itemize @bullet
10719: @item
10720: This model combines object oriented programming with information
10721: hiding. It helps you writing large application, where scoping is
10722: necessary, because it provides class-oriented scoping.
10723: 
10724: @item
10725: Named objects, object pointers, and object arrays can be created,
10726: selector invocation uses the ``object selector'' syntax. Selector invocation
10727: to objects and/or selectors on the stack is a bit less convenient, but
10728: possible.
10729: 
10730: @item
10731: Selector invocation and instance variable usage of the active object is
10732: straightforward, since both make use of the active object.
10733: 
10734: @item
10735: Late binding is efficient and easy to use.
10736: 
10737: @item
10738: State-smart objects parse selectors. However, extensibility is provided
10739: using a (parsing) selector @code{postpone} and a selector @code{'}.
10740: 
10741: @item
10742: An implementation in ANS Forth is available.
10743: 
10744: @end itemize
10745: 
10746: 
10747: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10748: @subsubsection Basic @file{oof.fs} Usage
10749: @cindex @file{oof.fs} usage
10750: 
10751: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10752: 
10753: You can define a class for graphical objects like this:
10754: 
10755: @cindex @code{class} usage
10756: @cindex @code{class;} usage
10757: @cindex @code{method} usage
10758: @example
10759: object class graphical \ "object" is the parent class
10760:   method draw ( x y -- )
10761: class;
10762: @end example
10763: 
10764: This code defines a class @code{graphical} with an
10765: operation @code{draw}.  We can perform the operation
10766: @code{draw} on any @code{graphical} object, e.g.:
10767: 
10768: @example
10769: 100 100 t-rex draw
10770: @end example
10771: 
10772: @noindent
10773: where @code{t-rex} is an object or object pointer, created with e.g.
10774: @code{graphical : t-rex}.
10775: 
10776: @cindex abstract class
10777: How do we create a graphical object? With the present definitions,
10778: we cannot create a useful graphical object. The class
10779: @code{graphical} describes graphical objects in general, but not
10780: any concrete graphical object type (C++ users would call it an
10781: @emph{abstract class}); e.g., there is no method for the selector
10782: @code{draw} in the class @code{graphical}.
10783: 
10784: For concrete graphical objects, we define child classes of the
10785: class @code{graphical}, e.g.:
10786: 
10787: @example
10788: graphical class circle \ "graphical" is the parent class
10789:   cell var circle-radius
10790: how:
10791:   : draw ( x y -- )
10792:     circle-radius @@ draw-circle ;
10793: 
10794:   : init ( n-radius -- )
10795:     circle-radius ! ;
10796: class;
10797: @end example
10798: 
10799: Here we define a class @code{circle} as a child of @code{graphical},
10800: with a field @code{circle-radius}; it defines new methods for the
10801: selectors @code{draw} and @code{init} (@code{init} is defined in
10802: @code{object}, the parent class of @code{graphical}).
10803: 
10804: Now we can create a circle in the dictionary with:
10805: 
10806: @example
10807: 50 circle : my-circle
10808: @end example
10809: 
10810: @noindent
10811: @code{:} invokes @code{init}, thus initializing the field
10812: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10813: with:
10814: 
10815: @example
10816: 100 100 my-circle draw
10817: @end example
10818: 
10819: @cindex selector invocation, restrictions
10820: @cindex class definition, restrictions
10821: Note: You can only invoke a selector if the receiving object belongs to
10822: the class where the selector was defined or one of its descendents;
10823: e.g., you can invoke @code{draw} only for objects belonging to
10824: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10825: mechanism will check if you try to invoke a selector that is not
10826: defined in this class hierarchy, so you'll get an error at compilation
10827: time.
10828: 
10829: 
10830: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10831: @subsubsection The @file{oof.fs} base class
10832: @cindex @file{oof.fs} base class
10833: 
10834: When you define a class, you have to specify a parent class.  So how do
10835: you start defining classes? There is one class available from the start:
10836: @code{object}. You have to use it as ancestor for all classes. It is the
10837: only class that has no parent. Classes are also objects, except that
10838: they don't have instance variables; class manipulation such as
10839: inheritance or changing definitions of a class is handled through
10840: selectors of the class @code{object}.
10841: 
10842: @code{object} provides a number of selectors:
10843: 
10844: @itemize @bullet
10845: @item
10846: @code{class} for subclassing, @code{definitions} to add definitions
10847: later on, and @code{class?} to get type informations (is the class a
10848: subclass of the class passed on the stack?).
10849: 
10850: doc---object-class
10851: doc---object-definitions
10852: doc---object-class?
10853: 
10854: 
10855: @item
10856: @code{init} and @code{dispose} as constructor and destructor of the
10857: object. @code{init} is invocated after the object's memory is allocated,
10858: while @code{dispose} also handles deallocation. Thus if you redefine
10859: @code{dispose}, you have to call the parent's dispose with @code{super
10860: dispose}, too.
10861: 
10862: doc---object-init
10863: doc---object-dispose
10864: 
10865: 
10866: @item
10867: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10868: @code{[]} to create named and unnamed objects and object arrays or
10869: object pointers.
10870: 
10871: doc---object-new
10872: doc---object-new[]
10873: doc---object-:
10874: doc---object-ptr
10875: doc---object-asptr
10876: doc---object-[]
10877: 
10878: 
10879: @item
10880: @code{::} and @code{super} for explicit scoping. You should use explicit
10881: scoping only for super classes or classes with the same set of instance
10882: variables. Explicitly-scoped selectors use early binding.
10883: 
10884: doc---object-::
10885: doc---object-super
10886: 
10887: 
10888: @item
10889: @code{self} to get the address of the object
10890: 
10891: doc---object-self
10892: 
10893: 
10894: @item
10895: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10896: pointers and instance defers.
10897: 
10898: doc---object-bind
10899: doc---object-bound
10900: doc---object-link
10901: doc---object-is
10902: 
10903: 
10904: @item
10905: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10906: form the stack, and @code{postpone} to generate selector invocation code.
10907: 
10908: doc---object-'
10909: doc---object-postpone
10910: 
10911: 
10912: @item
10913: @code{with} and @code{endwith} to select the active object from the
10914: stack, and enable its scope. Using @code{with} and @code{endwith}
10915: also allows you to create code using selector @code{postpone} without being
10916: trapped by the state-smart objects.
10917: 
10918: doc---object-with
10919: doc---object-endwith
10920: 
10921: 
10922: @end itemize
10923: 
10924: @node Class Declaration, Class Implementation, The OOF base class, OOF
10925: @subsubsection Class Declaration
10926: @cindex class declaration
10927: 
10928: @itemize @bullet
10929: @item
10930: Instance variables
10931: 
10932: doc---oof-var
10933: 
10934: 
10935: @item
10936: Object pointers
10937: 
10938: doc---oof-ptr
10939: doc---oof-asptr
10940: 
10941: 
10942: @item
10943: Instance defers
10944: 
10945: doc---oof-defer
10946: 
10947: 
10948: @item
10949: Method selectors
10950: 
10951: doc---oof-early
10952: doc---oof-method
10953: 
10954: 
10955: @item
10956: Class-wide variables
10957: 
10958: doc---oof-static
10959: 
10960: 
10961: @item
10962: End declaration
10963: 
10964: doc---oof-how:
10965: doc---oof-class;
10966: 
10967: 
10968: @end itemize
10969: 
10970: @c -------------------------------------------------------------
10971: @node Class Implementation,  , Class Declaration, OOF
10972: @subsubsection Class Implementation
10973: @cindex class implementation
10974: 
10975: @c -------------------------------------------------------------
10976: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10977: @subsection The @file{mini-oof.fs} model
10978: @cindex mini-oof
10979: 
10980: Gforth's third object oriented Forth package is a 12-liner. It uses a
10981: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
10982: and reduces to the bare minimum of features. This is based on a posting
10983: of Bernd Paysan in comp.lang.forth.
10984: 
10985: @menu
10986: * Basic Mini-OOF Usage::        
10987: * Mini-OOF Example::            
10988: * Mini-OOF Implementation::     
10989: @end menu
10990: 
10991: @c -------------------------------------------------------------
10992: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10993: @subsubsection Basic @file{mini-oof.fs} Usage
10994: @cindex mini-oof usage
10995: 
10996: There is a base class (@code{class}, which allocates one cell for the
10997: object pointer) plus seven other words: to define a method, a variable,
10998: a class; to end a class, to resolve binding, to allocate an object and
10999: to compile a class method.
11000: @comment TODO better description of the last one
11001: 
11002: 
11003: doc-object
11004: doc-method
11005: doc-var
11006: doc-class
11007: doc-end-class
11008: doc-defines
11009: doc-new
11010: doc-::
11011: 
11012: 
11013: 
11014: @c -------------------------------------------------------------
11015: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11016: @subsubsection Mini-OOF Example
11017: @cindex mini-oof example
11018: 
11019: A short example shows how to use this package. This example, in slightly
11020: extended form, is supplied as @file{moof-exm.fs}
11021: @comment TODO could flesh this out with some comments from the Forthwrite article
11022: 
11023: @example
11024: object class
11025:   method init
11026:   method draw
11027: end-class graphical
11028: @end example
11029: 
11030: This code defines a class @code{graphical} with an
11031: operation @code{draw}.  We can perform the operation
11032: @code{draw} on any @code{graphical} object, e.g.:
11033: 
11034: @example
11035: 100 100 t-rex draw
11036: @end example
11037: 
11038: where @code{t-rex} is an object or object pointer, created with e.g.
11039: @code{graphical new Constant t-rex}.
11040: 
11041: For concrete graphical objects, we define child classes of the
11042: class @code{graphical}, e.g.:
11043: 
11044: @example
11045: graphical class
11046:   cell var circle-radius
11047: end-class circle \ "graphical" is the parent class
11048: 
11049: :noname ( x y -- )
11050:   circle-radius @@ draw-circle ; circle defines draw
11051: :noname ( r -- )
11052:   circle-radius ! ; circle defines init
11053: @end example
11054: 
11055: There is no implicit init method, so we have to define one. The creation
11056: code of the object now has to call init explicitely.
11057: 
11058: @example
11059: circle new Constant my-circle
11060: 50 my-circle init
11061: @end example
11062: 
11063: It is also possible to add a function to create named objects with
11064: automatic call of @code{init}, given that all objects have @code{init}
11065: on the same place:
11066: 
11067: @example
11068: : new: ( .. o "name" -- )
11069:     new dup Constant init ;
11070: 80 circle new: large-circle
11071: @end example
11072: 
11073: We can draw this new circle at (100,100) with:
11074: 
11075: @example
11076: 100 100 my-circle draw
11077: @end example
11078: 
11079: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11080: @subsubsection @file{mini-oof.fs} Implementation
11081: 
11082: Object-oriented systems with late binding typically use a
11083: ``vtable''-approach: the first variable in each object is a pointer to a
11084: table, which contains the methods as function pointers. The vtable
11085: may also contain other information.
11086: 
11087: So first, let's declare selectors:
11088: 
11089: @example
11090: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11091:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11092: @end example
11093: 
11094: During selector declaration, the number of selectors and instance
11095: variables is on the stack (in address units). @code{method} creates one
11096: selector and increments the selector number. To execute a selector, it
11097: takes the object, fetches the vtable pointer, adds the offset, and
11098: executes the method @i{xt} stored there. Each selector takes the object
11099: it is invoked with as top of stack parameter; it passes the parameters
11100: (including the object) unchanged to the appropriate method which should
11101: consume that object.
11102: 
11103: Now, we also have to declare instance variables
11104: 
11105: @example
11106: : var ( m v size "name" -- m v' ) Create  over , +
11107:   DOES> ( o -- addr ) @@ + ;
11108: @end example
11109: 
11110: As before, a word is created with the current offset. Instance
11111: variables can have different sizes (cells, floats, doubles, chars), so
11112: all we do is take the size and add it to the offset. If your machine
11113: has alignment restrictions, put the proper @code{aligned} or
11114: @code{faligned} before the variable, to adjust the variable
11115: offset. That's why it is on the top of stack.
11116: 
11117: We need a starting point (the base object) and some syntactic sugar:
11118: 
11119: @example
11120: Create object  1 cells , 2 cells ,
11121: : class ( class -- class selectors vars ) dup 2@@ ;
11122: @end example
11123: 
11124: For inheritance, the vtable of the parent object has to be
11125: copied when a new, derived class is declared. This gives all the
11126: methods of the parent class, which can be overridden, though.
11127: 
11128: @example
11129: : end-class  ( class selectors vars "name" -- )
11130:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11131:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11132: @end example
11133: 
11134: The first line creates the vtable, initialized with
11135: @code{noop}s. The second line is the inheritance mechanism, it
11136: copies the xts from the parent vtable.
11137: 
11138: We still have no way to define new methods, let's do that now:
11139: 
11140: @example
11141: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11142: @end example
11143: 
11144: To allocate a new object, we need a word, too:
11145: 
11146: @example
11147: : new ( class -- o )  here over @@ allot swap over ! ;
11148: @end example
11149: 
11150: Sometimes derived classes want to access the method of the
11151: parent object. There are two ways to achieve this with Mini-OOF:
11152: first, you could use named words, and second, you could look up the
11153: vtable of the parent object.
11154: 
11155: @example
11156: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11157: @end example
11158: 
11159: 
11160: Nothing can be more confusing than a good example, so here is
11161: one. First let's declare a text object (called
11162: @code{button}), that stores text and position:
11163: 
11164: @example
11165: object class
11166:   cell var text
11167:   cell var len
11168:   cell var x
11169:   cell var y
11170:   method init
11171:   method draw
11172: end-class button
11173: @end example
11174: 
11175: @noindent
11176: Now, implement the two methods, @code{draw} and @code{init}:
11177: 
11178: @example
11179: :noname ( o -- )
11180:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11181:  button defines draw
11182: :noname ( addr u o -- )
11183:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11184:  button defines init
11185: @end example
11186: 
11187: @noindent
11188: To demonstrate inheritance, we define a class @code{bold-button}, with no
11189: new data and no new selectors:
11190: 
11191: @example
11192: button class
11193: end-class bold-button
11194: 
11195: : bold   27 emit ." [1m" ;
11196: : normal 27 emit ." [0m" ;
11197: @end example
11198: 
11199: @noindent
11200: The class @code{bold-button} has a different draw method to
11201: @code{button}, but the new method is defined in terms of the draw method
11202: for @code{button}:
11203: 
11204: @example
11205: :noname bold [ button :: draw ] normal ; bold-button defines draw
11206: @end example
11207: 
11208: @noindent
11209: Finally, create two objects and apply selectors:
11210: 
11211: @example
11212: button new Constant foo
11213: s" thin foo" foo init
11214: page
11215: foo draw
11216: bold-button new Constant bar
11217: s" fat bar" bar init
11218: 1 bar y !
11219: bar draw
11220: @end example
11221: 
11222: 
11223: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11224: @subsection Comparison with other object models
11225: @cindex comparison of object models
11226: @cindex object models, comparison
11227: 
11228: Many object-oriented Forth extensions have been proposed (@cite{A survey
11229: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11230: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11231: relation of the object models described here to two well-known and two
11232: closely-related (by the use of method maps) models.  Andras Zsoter
11233: helped us with this section.
11234: 
11235: @cindex Neon model
11236: The most popular model currently seems to be the Neon model (see
11237: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11238: 1997) by Andrew McKewan) but this model has a number of limitations
11239: @footnote{A longer version of this critique can be
11240: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11241: Dimensions, May 1997) by Anton Ertl.}:
11242: 
11243: @itemize @bullet
11244: @item
11245: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11246: to pass objects on the stack.
11247: 
11248: @item
11249: It requires that the selector parses the input stream (at
11250: compile time); this leads to reduced extensibility and to bugs that are
11251: hard to find.
11252: 
11253: @item
11254: It allows using every selector on every object; this eliminates the
11255: need for interfaces, but makes it harder to create efficient
11256: implementations.
11257: @end itemize
11258: 
11259: @cindex Pountain's object-oriented model
11260: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11261: Press, London, 1987) by Dick Pountain. However, it is not really about
11262: object-oriented programming, because it hardly deals with late
11263: binding. Instead, it focuses on features like information hiding and
11264: overloading that are characteristic of modular languages like Ada (83).
11265: 
11266: @cindex Zsoter's object-oriented model
11267: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11268: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11269: describes a model that makes heavy use of an active object (like
11270: @code{this} in @file{objects.fs}): The active object is not only used
11271: for accessing all fields, but also specifies the receiving object of
11272: every selector invocation; you have to change the active object
11273: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11274: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11275: the method entry point is unnecessary with Zsoter's model, because the
11276: receiving object is the active object already. On the other hand, the
11277: explicit change is absolutely necessary in that model, because otherwise
11278: no one could ever change the active object. An ANS Forth implementation
11279: of this model is available through
11280: @uref{http://www.forth.org/oopf.html}.
11281: 
11282: @cindex @file{oof.fs}, differences to other models
11283: The @file{oof.fs} model combines information hiding and overloading
11284: resolution (by keeping names in various word lists) with object-oriented
11285: programming. It sets the active object implicitly on method entry, but
11286: also allows explicit changing (with @code{>o...o>} or with
11287: @code{with...endwith}). It uses parsing and state-smart objects and
11288: classes for resolving overloading and for early binding: the object or
11289: class parses the selector and determines the method from this. If the
11290: selector is not parsed by an object or class, it performs a call to the
11291: selector for the active object (late binding), like Zsoter's model.
11292: Fields are always accessed through the active object. The big
11293: disadvantage of this model is the parsing and the state-smartness, which
11294: reduces extensibility and increases the opportunities for subtle bugs;
11295: essentially, you are only safe if you never tick or @code{postpone} an
11296: object or class (Bernd disagrees, but I (Anton) am not convinced).
11297: 
11298: @cindex @file{mini-oof.fs}, differences to other models
11299: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11300: version of the @file{objects.fs} model, but syntactically it is a
11301: mixture of the @file{objects.fs} and @file{oof.fs} models.
11302: 
11303: 
11304: @c -------------------------------------------------------------
11305: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11306: @section Programming Tools
11307: @cindex programming tools
11308: 
11309: @c !! move this and assembler down below OO stuff.
11310: 
11311: @menu
11312: * Examining::                   
11313: * Forgetting words::            
11314: * Debugging::                   Simple and quick.
11315: * Assertions::                  Making your programs self-checking.
11316: * Singlestep Debugger::         Executing your program word by word.
11317: @end menu
11318: 
11319: @node Examining, Forgetting words, Programming Tools, Programming Tools
11320: @subsection Examining data and code
11321: @cindex examining data and code
11322: @cindex data examination
11323: @cindex code examination
11324: 
11325: The following words inspect the stack non-destructively:
11326: 
11327: doc-.s
11328: doc-f.s
11329: 
11330: There is a word @code{.r} but it does @i{not} display the return stack!
11331: It is used for formatted numeric output (@pxref{Simple numeric output}).
11332: 
11333: doc-depth
11334: doc-fdepth
11335: doc-clearstack
11336: doc-clearstacks
11337: 
11338: The following words inspect memory.
11339: 
11340: doc-?
11341: doc-dump
11342: 
11343: And finally, @code{see} allows to inspect code:
11344: 
11345: doc-see
11346: doc-xt-see
11347: doc-simple-see
11348: doc-simple-see-range
11349: 
11350: @node Forgetting words, Debugging, Examining, Programming Tools
11351: @subsection Forgetting words
11352: @cindex words, forgetting
11353: @cindex forgeting words
11354: 
11355: @c  anton: other, maybe better places for this subsection: Defining Words;
11356: @c  Dictionary allocation.  At least a reference should be there.
11357: 
11358: Forth allows you to forget words (and everything that was alloted in the
11359: dictonary after them) in a LIFO manner.
11360: 
11361: doc-marker
11362: 
11363: The most common use of this feature is during progam development: when
11364: you change a source file, forget all the words it defined and load it
11365: again (since you also forget everything defined after the source file
11366: was loaded, you have to reload that, too).  Note that effects like
11367: storing to variables and destroyed system words are not undone when you
11368: forget words.  With a system like Gforth, that is fast enough at
11369: starting up and compiling, I find it more convenient to exit and restart
11370: Gforth, as this gives me a clean slate.
11371: 
11372: Here's an example of using @code{marker} at the start of a source file
11373: that you are debugging; it ensures that you only ever have one copy of
11374: the file's definitions compiled at any time:
11375: 
11376: @example
11377: [IFDEF] my-code
11378:     my-code
11379: [ENDIF]
11380: 
11381: marker my-code
11382: init-included-files
11383: 
11384: \ .. definitions start here
11385: \ .
11386: \ .
11387: \ end
11388: @end example
11389: 
11390: 
11391: @node Debugging, Assertions, Forgetting words, Programming Tools
11392: @subsection Debugging
11393: @cindex debugging
11394: 
11395: Languages with a slow edit/compile/link/test development loop tend to
11396: require sophisticated tracing/stepping debuggers to facilate debugging.
11397: 
11398: A much better (faster) way in fast-compiling languages is to add
11399: printing code at well-selected places, let the program run, look at
11400: the output, see where things went wrong, add more printing code, etc.,
11401: until the bug is found.
11402: 
11403: The simple debugging aids provided in @file{debugs.fs}
11404: are meant to support this style of debugging.
11405: 
11406: The word @code{~~} prints debugging information (by default the source
11407: location and the stack contents). It is easy to insert. If you use Emacs
11408: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11409: query-replace them with nothing). The deferred words
11410: @code{printdebugdata} and @code{.debugline} control the output of
11411: @code{~~}. The default source location output format works well with
11412: Emacs' compilation mode, so you can step through the program at the
11413: source level using @kbd{C-x `} (the advantage over a stepping debugger
11414: is that you can step in any direction and you know where the crash has
11415: happened or where the strange data has occurred).
11416: 
11417: doc-~~
11418: doc-printdebugdata
11419: doc-.debugline
11420: 
11421: @cindex filenames in @code{~~} output
11422: @code{~~} (and assertions) will usually print the wrong file name if a
11423: marker is executed in the same file after their occurance.  They will
11424: print @samp{*somewhere*} as file name if a marker is executed in the
11425: same file before their occurance.
11426: 
11427: 
11428: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11429: @subsection Assertions
11430: @cindex assertions
11431: 
11432: It is a good idea to make your programs self-checking, especially if you
11433: make an assumption that may become invalid during maintenance (for
11434: example, that a certain field of a data structure is never zero). Gforth
11435: supports @dfn{assertions} for this purpose. They are used like this:
11436: 
11437: @example
11438: assert( @i{flag} )
11439: @end example
11440: 
11441: The code between @code{assert(} and @code{)} should compute a flag, that
11442: should be true if everything is alright and false otherwise. It should
11443: not change anything else on the stack. The overall stack effect of the
11444: assertion is @code{( -- )}. E.g.
11445: 
11446: @example
11447: assert( 1 1 + 2 = ) \ what we learn in school
11448: assert( dup 0<> ) \ assert that the top of stack is not zero
11449: assert( false ) \ this code should not be reached
11450: @end example
11451: 
11452: The need for assertions is different at different times. During
11453: debugging, we want more checking, in production we sometimes care more
11454: for speed. Therefore, assertions can be turned off, i.e., the assertion
11455: becomes a comment. Depending on the importance of an assertion and the
11456: time it takes to check it, you may want to turn off some assertions and
11457: keep others turned on. Gforth provides several levels of assertions for
11458: this purpose:
11459: 
11460: 
11461: doc-assert0(
11462: doc-assert1(
11463: doc-assert2(
11464: doc-assert3(
11465: doc-assert(
11466: doc-)
11467: 
11468: 
11469: The variable @code{assert-level} specifies the highest assertions that
11470: are turned on. I.e., at the default @code{assert-level} of one,
11471: @code{assert0(} and @code{assert1(} assertions perform checking, while
11472: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11473: 
11474: The value of @code{assert-level} is evaluated at compile-time, not at
11475: run-time. Therefore you cannot turn assertions on or off at run-time;
11476: you have to set the @code{assert-level} appropriately before compiling a
11477: piece of code. You can compile different pieces of code at different
11478: @code{assert-level}s (e.g., a trusted library at level 1 and
11479: newly-written code at level 3).
11480: 
11481: 
11482: doc-assert-level
11483: 
11484: 
11485: If an assertion fails, a message compatible with Emacs' compilation mode
11486: is produced and the execution is aborted (currently with @code{ABORT"}.
11487: If there is interest, we will introduce a special throw code. But if you
11488: intend to @code{catch} a specific condition, using @code{throw} is
11489: probably more appropriate than an assertion).
11490: 
11491: @cindex filenames in assertion output
11492: Assertions (and @code{~~}) will usually print the wrong file name if a
11493: marker is executed in the same file after their occurance.  They will
11494: print @samp{*somewhere*} as file name if a marker is executed in the
11495: same file before their occurance.
11496: 
11497: Definitions in ANS Forth for these assertion words are provided
11498: in @file{compat/assert.fs}.
11499: 
11500: 
11501: @node Singlestep Debugger,  , Assertions, Programming Tools
11502: @subsection Singlestep Debugger
11503: @cindex singlestep Debugger
11504: @cindex debugging Singlestep
11505: 
11506: The singlestep debugger does not work in this release.
11507: 
11508: When you create a new word there's often the need to check whether it
11509: behaves correctly or not. You can do this by typing @code{dbg
11510: badword}. A debug session might look like this:
11511: 
11512: @example
11513: : badword 0 DO i . LOOP ;  ok
11514: 2 dbg badword 
11515: : badword  
11516: Scanning code...
11517: 
11518: Nesting debugger ready!
11519: 
11520: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11521: 400D4740  8049F68 DO             -> [ 0 ] 
11522: 400D4744  804A0C8 i              -> [ 1 ] 00000 
11523: 400D4748 400C5E60 .              -> 0 [ 0 ] 
11524: 400D474C  8049D0C LOOP           -> [ 0 ] 
11525: 400D4744  804A0C8 i              -> [ 1 ] 00001 
11526: 400D4748 400C5E60 .              -> 1 [ 0 ] 
11527: 400D474C  8049D0C LOOP           -> [ 0 ] 
11528: 400D4758  804B384 ;              ->  ok
11529: @end example
11530: 
11531: Each line displayed is one step. You always have to hit return to
11532: execute the next word that is displayed. If you don't want to execute
11533: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11534: an overview what keys are available:
11535: 
11536: @table @i
11537: 
11538: @item @key{RET}
11539: Next; Execute the next word.
11540: 
11541: @item n
11542: Nest; Single step through next word.
11543: 
11544: @item u
11545: Unnest; Stop debugging and execute rest of word. If we got to this word
11546: with nest, continue debugging with the calling word.
11547: 
11548: @item d
11549: Done; Stop debugging and execute rest.
11550: 
11551: @item s
11552: Stop; Abort immediately.
11553: 
11554: @end table
11555: 
11556: Debugging large application with this mechanism is very difficult, because
11557: you have to nest very deeply into the program before the interesting part
11558: begins. This takes a lot of time. 
11559: 
11560: To do it more directly put a @code{BREAK:} command into your source code.
11561: When program execution reaches @code{BREAK:} the single step debugger is
11562: invoked and you have all the features described above.
11563: 
11564: If you have more than one part to debug it is useful to know where the
11565: program has stopped at the moment. You can do this by the 
11566: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11567: string is typed out when the ``breakpoint'' is reached.
11568: 
11569: 
11570: doc-dbg
11571: doc-break:
11572: doc-break"
11573: 
11574: 
11575: 
11576: @c -------------------------------------------------------------
11577: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11578: @section Assembler and Code Words
11579: @cindex assembler
11580: @cindex code words
11581: 
11582: @menu
11583: * Code and ;code::              
11584: * Common Assembler::            Assembler Syntax
11585: * Common Disassembler::         
11586: * 386 Assembler::               Deviations and special cases
11587: * Alpha Assembler::             Deviations and special cases
11588: * MIPS assembler::              Deviations and special cases
11589: * Other assemblers::            How to write them
11590: @end menu
11591: 
11592: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11593: @subsection @code{Code} and @code{;code}
11594: 
11595: Gforth provides some words for defining primitives (words written in
11596: machine code), and for defining the machine-code equivalent of
11597: @code{DOES>}-based defining words. However, the machine-independent
11598: nature of Gforth poses a few problems: First of all, Gforth runs on
11599: several architectures, so it can provide no standard assembler. What's
11600: worse is that the register allocation not only depends on the processor,
11601: but also on the @code{gcc} version and options used.
11602: 
11603: The words that Gforth offers encapsulate some system dependences (e.g.,
11604: the header structure), so a system-independent assembler may be used in
11605: Gforth. If you do not have an assembler, you can compile machine code
11606: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11607: because these words emit stuff in @i{data} space; it works because
11608: Gforth has unified code/data spaces. Assembler isn't likely to be
11609: portable anyway.}.
11610: 
11611: 
11612: doc-assembler
11613: doc-init-asm
11614: doc-code
11615: doc-end-code
11616: doc-;code
11617: doc-flush-icache
11618: 
11619: 
11620: If @code{flush-icache} does not work correctly, @code{code} words
11621: etc. will not work (reliably), either.
11622: 
11623: The typical usage of these @code{code} words can be shown most easily by
11624: analogy to the equivalent high-level defining words:
11625: 
11626: @example
11627: : foo                              code foo
11628:    <high-level Forth words>              <assembler>
11629: ;                                  end-code
11630:                                 
11631: : bar                              : bar
11632:    <high-level Forth words>           <high-level Forth words>
11633:    CREATE                             CREATE
11634:       <high-level Forth words>           <high-level Forth words>
11635:    DOES>                              ;code
11636:       <high-level Forth words>           <assembler>
11637: ;                                  end-code
11638: @end example
11639: 
11640: @c anton: the following stuff is also in "Common Assembler", in less detail.
11641: 
11642: @cindex registers of the inner interpreter
11643: In the assembly code you will want to refer to the inner interpreter's
11644: registers (e.g., the data stack pointer) and you may want to use other
11645: registers for temporary storage. Unfortunately, the register allocation
11646: is installation-dependent.
11647: 
11648: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11649: (return stack pointer) may be in different places in @code{gforth} and
11650: @code{gforth-fast}, or different installations.  This means that you
11651: cannot write a @code{NEXT} routine that works reliably on both versions
11652: or different installations; so for doing @code{NEXT}, I recommend
11653: jumping to @code{' noop >code-address}, which contains nothing but a
11654: @code{NEXT}.
11655: 
11656: For general accesses to the inner interpreter's registers, the easiest
11657: solution is to use explicit register declarations (@pxref{Explicit Reg
11658: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11659: all of the inner interpreter's registers: You have to compile Gforth
11660: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11661: the appropriate declarations must be present in the @code{machine.h}
11662: file (see @code{mips.h} for an example; you can find a full list of all
11663: declarable register symbols with @code{grep register engine.c}). If you
11664: give explicit registers to all variables that are declared at the
11665: beginning of @code{engine()}, you should be able to use the other
11666: caller-saved registers for temporary storage. Alternatively, you can use
11667: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11668: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11669: reserve a register (however, this restriction on register allocation may
11670: slow Gforth significantly).
11671: 
11672: If this solution is not viable (e.g., because @code{gcc} does not allow
11673: you to explicitly declare all the registers you need), you have to find
11674: out by looking at the code where the inner interpreter's registers
11675: reside and which registers can be used for temporary storage. You can
11676: get an assembly listing of the engine's code with @code{make engine.s}.
11677: 
11678: In any case, it is good practice to abstract your assembly code from the
11679: actual register allocation. E.g., if the data stack pointer resides in
11680: register @code{$17}, create an alias for this register called @code{sp},
11681: and use that in your assembly code.
11682: 
11683: @cindex code words, portable
11684: Another option for implementing normal and defining words efficiently
11685: is to add the desired functionality to the source of Gforth. For normal
11686: words you just have to edit @file{primitives} (@pxref{Automatic
11687: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11688: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11689: @file{prims2x.fs}, and possibly @file{cross.fs}.
11690: 
11691: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11692: @subsection Common Assembler
11693: 
11694: The assemblers in Gforth generally use a postfix syntax, i.e., the
11695: instruction name follows the operands.
11696: 
11697: The operands are passed in the usual order (the same that is used in the
11698: manual of the architecture).  Since they all are Forth words, they have
11699: to be separated by spaces; you can also use Forth words to compute the
11700: operands.
11701: 
11702: The instruction names usually end with a @code{,}.  This makes it easier
11703: to visually separate instructions if you put several of them on one
11704: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11705: 
11706: Registers are usually specified by number; e.g., (decimal) @code{11}
11707: specifies registers R11 and F11 on the Alpha architecture (which one,
11708: depends on the instruction).  The usual names are also available, e.g.,
11709: @code{s2} for R11 on Alpha.
11710: 
11711: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11712: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11713: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11714: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
11715: conditions are specified in a way specific to each assembler.
11716: 
11717: Note that the register assignments of the Gforth engine can change
11718: between Gforth versions, or even between different compilations of the
11719: same Gforth version (e.g., if you use a different GCC version).  So if
11720: you want to refer to Gforth's registers (e.g., the stack pointer or
11721: TOS), I recommend defining your own words for refering to these
11722: registers, and using them later on; then you can easily adapt to a
11723: changed register assignment.  The stability of the register assignment
11724: is usually better if you build Gforth with @code{--enable-force-reg}.
11725: 
11726: The most common use of these registers is to dispatch to the next word
11727: (the @code{next} routine).  A portable way to do this is to jump to
11728: @code{' noop >code-address} (of course, this is less efficient than
11729: integrating the @code{next} code and scheduling it well).
11730: 
11731: Another difference between Gforth version is that the top of stack is
11732: kept in memory in @code{gforth} and, on most platforms, in a register in
11733: @code{gforth-fast}.
11734: 
11735: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11736: @subsection Common Disassembler
11737: @cindex disassembler, general
11738: @cindex gdb disassembler
11739: 
11740: You can disassemble a @code{code} word with @code{see}
11741: (@pxref{Debugging}).  You can disassemble a section of memory with
11742: 
11743: doc-discode
11744: 
11745: There are two kinds of disassembler for Gforth: The Forth disassembler
11746: (available on some CPUs) and the gdb disassembler (available on
11747: platforms with @command{gdb} and @command{mktemp}).  If both are
11748: available, the Forth disassembler is used by default.  If you prefer
11749: the gdb disassembler, say
11750: 
11751: @example
11752: ' disasm-gdb is discode
11753: @end example
11754: 
11755: If neither is available, @code{discode} performs @code{dump}.
11756: 
11757: The Forth disassembler generally produces output that can be fed into the
11758: assembler (i.e., same syntax, etc.).  It also includes additional
11759: information in comments.  In particular, the address of the instruction
11760: is given in a comment before the instruction.
11761: 
11762: The gdb disassembler produces output in the same format as the gdb
11763: @code{disassemble} command (@pxref{Machine Code,,Source and machine
11764: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
11765: the 386 and AMD64 architectures).
11766: 
11767: @code{See} may display more or less than the actual code of the word,
11768: because the recognition of the end of the code is unreliable.  You can
11769: use @code{discode} if it did not display enough.  It may display more, if
11770: the code word is not immediately followed by a named word.  If you have
11771: something else there, you can follow the word with @code{align latest ,}
11772: to ensure that the end is recognized.
11773: 
11774: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11775: @subsection 386 Assembler
11776: 
11777: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11778: available under GPL, and originally part of bigFORTH.
11779: 
11780: The 386 disassembler included in Gforth was written by Andrew McKewan
11781: and is in the public domain.
11782: 
11783: The disassembler displays code in an Intel-like prefix syntax.
11784: 
11785: The assembler uses a postfix syntax with reversed parameters.
11786: 
11787: The assembler includes all instruction of the Athlon, i.e. 486 core
11788: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11789: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11790: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
11791: 
11792: There are several prefixes to switch between different operation sizes,
11793: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11794: double-word accesses. Addressing modes can be switched with @code{.wa}
11795: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11796: need a prefix for byte register names (@code{AL} et al).
11797: 
11798: For floating point operations, the prefixes are @code{.fs} (IEEE
11799: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11800: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
11801: 
11802: The MMX opcodes don't have size prefixes, they are spelled out like in
11803: the Intel assembler. Instead of move from and to memory, there are
11804: PLDQ/PLDD and PSTQ/PSTD.
11805: 
11806: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11807: ax.  Immediate values are indicated by postfixing them with @code{#},
11808: e.g., @code{3 #}.  Here are some examples of addressing modes in various
11809: syntaxes:
11810: 
11811: @example
11812: Gforth          Intel (NASM)   AT&T (gas)      Name
11813: .w ax           ax             %ax             register (16 bit)
11814: ax              eax            %eax            register (32 bit)
11815: 3 #             offset 3       $3              immediate
11816: 1000 #)         byte ptr 1000  1000            displacement
11817: bx )            [ebx]          (%ebx)          base
11818: 100 di d)       100[edi]       100(%edi)       base+displacement
11819: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
11820: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
11821: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
11822: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11823: @end example
11824: 
11825: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11826: @code{DI)} to enforce 32-bit displacement fields (useful for
11827: later patching).
11828: 
11829: Some example of instructions are:
11830: 
11831: @example
11832: ax bx mov             \ move ebx,eax
11833: 3 # ax mov            \ mov eax,3
11834: 100 di d) ax mov      \ mov eax,100[edi]
11835: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
11836: .w ax bx mov          \ mov bx,ax
11837: @end example
11838: 
11839: The following forms are supported for binary instructions:
11840: 
11841: @example
11842: <reg> <reg> <inst>
11843: <n> # <reg> <inst>
11844: <mem> <reg> <inst>
11845: <reg> <mem> <inst>
11846: <n> # <mem> <inst>
11847: @end example
11848: 
11849: The shift/rotate syntax is:
11850: 
11851: @example
11852: <reg/mem> 1 # shl \ shortens to shift without immediate
11853: <reg/mem> 4 # shl
11854: <reg/mem> cl shl
11855: @end example
11856: 
11857: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11858: the byte version.
11859: 
11860: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11861: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11862: pc < >= <= >}. (Note that most of these words shadow some Forth words
11863: when @code{assembler} is in front of @code{forth} in the search path,
11864: e.g., in @code{code} words).  Currently the control structure words use
11865: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11866: to shuffle them (you can also use @code{swap} etc.).
11867: 
11868: Here is an example of a @code{code} word (assumes that the stack pointer
11869: is in esi and the TOS is in ebx):
11870: 
11871: @example
11872: code my+ ( n1 n2 -- n )
11873:     4 si D) bx add
11874:     4 # si add
11875:     Next
11876: end-code
11877: @end example
11878: 
11879: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11880: @subsection Alpha Assembler
11881: 
11882: The Alpha assembler and disassembler were originally written by Bernd
11883: Thallner.
11884: 
11885: The register names @code{a0}--@code{a5} are not available to avoid
11886: shadowing hex numbers.
11887: 
11888: Immediate forms of arithmetic instructions are distinguished by a
11889: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11890: does not count as arithmetic instruction).
11891: 
11892: You have to specify all operands to an instruction, even those that
11893: other assemblers consider optional, e.g., the destination register for
11894: @code{br,}, or the destination register and hint for @code{jmp,}.
11895: 
11896: You can specify conditions for @code{if,} by removing the first @code{b}
11897: and the trailing @code{,} from a branch with a corresponding name; e.g.,
11898: 
11899: @example
11900: 11 fgt if, \ if F11>0e
11901:   ...
11902: endif,
11903: @end example
11904: 
11905: @code{fbgt,} gives @code{fgt}.  
11906: 
11907: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11908: @subsection MIPS assembler
11909: 
11910: The MIPS assembler was originally written by Christian Pirker.
11911: 
11912: Currently the assembler and disassembler only cover the MIPS-I
11913: architecture (R3000), and don't support FP instructions.
11914: 
11915: The register names @code{$a0}--@code{$a3} are not available to avoid
11916: shadowing hex numbers.
11917: 
11918: Because there is no way to distinguish registers from immediate values,
11919: you have to explicitly use the immediate forms of instructions, i.e.,
11920: @code{addiu,}, not just @code{addu,} (@command{as} does this
11921: implicitly).
11922: 
11923: If the architecture manual specifies several formats for the instruction
11924: (e.g., for @code{jalr,}), you usually have to use the one with more
11925: arguments (i.e., two for @code{jalr,}).  When in doubt, see
11926: @code{arch/mips/testasm.fs} for an example of correct use.
11927: 
11928: Branches and jumps in the MIPS architecture have a delay slot.  You have
11929: to fill it yourself (the simplest way is to use @code{nop,}), the
11930: assembler does not do it for you (unlike @command{as}).  Even
11931: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11932: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
11933: and @code{then,} just specify branch targets, they are not affected.
11934: 
11935: Note that you must not put branches, jumps, or @code{li,} into the delay
11936: slot: @code{li,} may expand to several instructions, and control flow
11937: instructions may not be put into the branch delay slot in any case.
11938: 
11939: For branches the argument specifying the target is a relative address;
11940: You have to add the address of the delay slot to get the absolute
11941: address.
11942: 
11943: The MIPS architecture also has load delay slots and restrictions on
11944: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11945: yourself to satisfy these restrictions, the assembler does not do it for
11946: you.
11947: 
11948: You can specify the conditions for @code{if,} etc. by taking a
11949: conditional branch and leaving away the @code{b} at the start and the
11950: @code{,} at the end.  E.g.,
11951: 
11952: @example
11953: 4 5 eq if,
11954:   ... \ do something if $4 equals $5
11955: then,
11956: @end example
11957: 
11958: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
11959: @subsection Other assemblers
11960: 
11961: If you want to contribute another assembler/disassembler, please contact
11962: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
11963: an assembler already.  If you are writing them from scratch, please use
11964: a similar syntax style as the one we use (i.e., postfix, commas at the
11965: end of the instruction names, @pxref{Common Assembler}); make the output
11966: of the disassembler be valid input for the assembler, and keep the style
11967: similar to the style we used.
11968: 
11969: Hints on implementation: The most important part is to have a good test
11970: suite that contains all instructions.  Once you have that, the rest is
11971: easy.  For actual coding you can take a look at
11972: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11973: the assembler and disassembler, avoiding redundancy and some potential
11974: bugs.  You can also look at that file (and @pxref{Advanced does> usage
11975: example}) to get ideas how to factor a disassembler.
11976: 
11977: Start with the disassembler, because it's easier to reuse data from the
11978: disassembler for the assembler than the other way round.
11979: 
11980: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11981: how simple it can be.
11982: 
11983: @c -------------------------------------------------------------
11984: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11985: @section Threading Words
11986: @cindex threading words
11987: 
11988: @cindex code address
11989: These words provide access to code addresses and other threading stuff
11990: in Gforth (and, possibly, other interpretive Forths). It more or less
11991: abstracts away the differences between direct and indirect threading
11992: (and, for direct threading, the machine dependences). However, at
11993: present this wordset is still incomplete. It is also pretty low-level;
11994: some day it will hopefully be made unnecessary by an internals wordset
11995: that abstracts implementation details away completely.
11996: 
11997: The terminology used here stems from indirect threaded Forth systems; in
11998: such a system, the XT of a word is represented by the CFA (code field
11999: address) of a word; the CFA points to a cell that contains the code
12000: address.  The code address is the address of some machine code that
12001: performs the run-time action of invoking the word (e.g., the
12002: @code{dovar:} routine pushes the address of the body of the word (a
12003: variable) on the stack
12004: ).
12005: 
12006: @cindex code address
12007: @cindex code field address
12008: In an indirect threaded Forth, you can get the code address of @i{name}
12009: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12010: >code-address}, independent of the threading method.
12011: 
12012: doc-threading-method
12013: doc->code-address
12014: doc-code-address!
12015: 
12016: @cindex @code{does>}-handler
12017: @cindex @code{does>}-code
12018: For a word defined with @code{DOES>}, the code address usually points to
12019: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12020: routine (in Gforth on some platforms, it can also point to the dodoes
12021: routine itself).  What you are typically interested in, though, is
12022: whether a word is a @code{DOES>}-defined word, and what Forth code it
12023: executes; @code{>does-code} tells you that.
12024: 
12025: doc->does-code
12026: 
12027: To create a @code{DOES>}-defined word with the following basic words,
12028: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12029: @code{/does-handler} aus behind you have to place your executable Forth
12030: code.  Finally you have to create a word and modify its behaviour with
12031: @code{does-handler!}.
12032: 
12033: doc-does-code!
12034: doc-does-handler!
12035: doc-/does-handler
12036: 
12037: The code addresses produced by various defining words are produced by
12038: the following words:
12039: 
12040: doc-docol:
12041: doc-docon:
12042: doc-dovar:
12043: doc-douser:
12044: doc-dodefer:
12045: doc-dofield:
12046: 
12047: @cindex definer
12048: The following two words generalize @code{>code-address},
12049: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12050: 
12051: doc->definer
12052: doc-definer!
12053: 
12054: @c -------------------------------------------------------------
12055: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
12056: @section Passing Commands to the Operating System
12057: @cindex operating system - passing commands
12058: @cindex shell commands
12059: 
12060: Gforth allows you to pass an arbitrary string to the host operating
12061: system shell (if such a thing exists) for execution.
12062: 
12063: doc-sh
12064: doc-system
12065: doc-$?
12066: doc-getenv
12067: 
12068: @c -------------------------------------------------------------
12069: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12070: @section Keeping track of Time
12071: @cindex time-related words
12072: 
12073: doc-ms
12074: doc-time&date
12075: doc-utime
12076: doc-cputime
12077: 
12078: 
12079: @c -------------------------------------------------------------
12080: @node Miscellaneous Words,  , Keeping track of Time, Words
12081: @section Miscellaneous Words
12082: @cindex miscellaneous words
12083: 
12084: @comment TODO find homes for these
12085: 
12086: These section lists the ANS Forth words that are not documented
12087: elsewhere in this manual. Ultimately, they all need proper homes.
12088: 
12089: doc-quit
12090: 
12091: The following ANS Forth words are not currently supported by Gforth 
12092: (@pxref{ANS conformance}):
12093: 
12094: @code{EDITOR} 
12095: @code{EMIT?} 
12096: @code{FORGET} 
12097: 
12098: @c ******************************************************************
12099: @node Error messages, Tools, Words, Top
12100: @chapter Error messages
12101: @cindex error messages
12102: @cindex backtrace
12103: 
12104: A typical Gforth error message looks like this:
12105: 
12106: @example
12107: in file included from \evaluated string/:-1
12108: in file included from ./yyy.fs:1
12109: ./xxx.fs:4: Invalid memory address
12110: >>>bar<<<
12111: Backtrace:
12112: $400E664C @@
12113: $400E6664 foo
12114: @end example
12115: 
12116: The message identifying the error is @code{Invalid memory address}.  The
12117: error happened when text-interpreting line 4 of the file
12118: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12119: word on the line where the error happened, is pointed out (with
12120: @code{>>>} and @code{<<<}).
12121: 
12122: The file containing the error was included in line 1 of @file{./yyy.fs},
12123: and @file{yyy.fs} was included from a non-file (in this case, by giving
12124: @file{yyy.fs} as command-line parameter to Gforth).
12125: 
12126: At the end of the error message you find a return stack dump that can be
12127: interpreted as a backtrace (possibly empty). On top you find the top of
12128: the return stack when the @code{throw} happened, and at the bottom you
12129: find the return stack entry just above the return stack of the topmost
12130: text interpreter.
12131: 
12132: To the right of most return stack entries you see a guess for the word
12133: that pushed that return stack entry as its return address. This gives a
12134: backtrace. In our case we see that @code{bar} called @code{foo}, and
12135: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12136: address} exception).
12137: 
12138: Note that the backtrace is not perfect: We don't know which return stack
12139: entries are return addresses (so we may get false positives); and in
12140: some cases (e.g., for @code{abort"}) we cannot determine from the return
12141: address the word that pushed the return address, so for some return
12142: addresses you see no names in the return stack dump.
12143: 
12144: @cindex @code{catch} and backtraces
12145: The return stack dump represents the return stack at the time when a
12146: specific @code{throw} was executed.  In programs that make use of
12147: @code{catch}, it is not necessarily clear which @code{throw} should be
12148: used for the return stack dump (e.g., consider one @code{throw} that
12149: indicates an error, which is caught, and during recovery another error
12150: happens; which @code{throw} should be used for the stack dump?).  Gforth
12151: presents the return stack dump for the first @code{throw} after the last
12152: executed (not returned-to) @code{catch}; this works well in the usual
12153: case.
12154: 
12155: @cindex @code{gforth-fast} and backtraces
12156: @cindex @code{gforth-fast}, difference from @code{gforth}
12157: @cindex backtraces with @code{gforth-fast}
12158: @cindex return stack dump with @code{gforth-fast}
12159: @code{Gforth} is able to do a return stack dump for throws generated
12160: from primitives (e.g., invalid memory address, stack empty etc.);
12161: @code{gforth-fast} is only able to do a return stack dump from a
12162: directly called @code{throw} (including @code{abort} etc.).  Given an
12163: exception caused by a primitive in @code{gforth-fast}, you will
12164: typically see no return stack dump at all; however, if the exception is
12165: caught by @code{catch} (e.g., for restoring some state), and then
12166: @code{throw}n again, the return stack dump will be for the first such
12167: @code{throw}.
12168: 
12169: @c ******************************************************************
12170: @node Tools, ANS conformance, Error messages, Top
12171: @chapter Tools
12172: 
12173: @menu
12174: * ANS Report::                  Report the words used, sorted by wordset.
12175: * Stack depth changes::         Where does this stack item come from?
12176: @end menu
12177: 
12178: See also @ref{Emacs and Gforth}.
12179: 
12180: @node ANS Report, Stack depth changes, Tools, Tools
12181: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12182: @cindex @file{ans-report.fs}
12183: @cindex report the words used in your program
12184: @cindex words used in your program
12185: 
12186: If you want to label a Forth program as ANS Forth Program, you must
12187: document which wordsets the program uses; for extension wordsets, it is
12188: helpful to list the words the program requires from these wordsets
12189: (because Forth systems are allowed to provide only some words of them).
12190: 
12191: The @file{ans-report.fs} tool makes it easy for you to determine which
12192: words from which wordset and which non-ANS words your application
12193: uses. You simply have to include @file{ans-report.fs} before loading the
12194: program you want to check. After loading your program, you can get the
12195: report with @code{print-ans-report}. A typical use is to run this as
12196: batch job like this:
12197: @example
12198: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12199: @end example
12200: 
12201: The output looks like this (for @file{compat/control.fs}):
12202: @example
12203: The program uses the following words
12204: from CORE :
12205: : POSTPONE THEN ; immediate ?dup IF 0= 
12206: from BLOCK-EXT :
12207: \ 
12208: from FILE :
12209: ( 
12210: @end example
12211: 
12212: @subsection Caveats
12213: 
12214: Note that @file{ans-report.fs} just checks which words are used, not whether
12215: they are used in an ANS Forth conforming way!
12216: 
12217: Some words are defined in several wordsets in the
12218: standard. @file{ans-report.fs} reports them for only one of the
12219: wordsets, and not necessarily the one you expect. It depends on usage
12220: which wordset is the right one to specify. E.g., if you only use the
12221: compilation semantics of @code{S"}, it is a Core word; if you also use
12222: its interpretation semantics, it is a File word.
12223: 
12224: 
12225: @node Stack depth changes,  , ANS Report, Tools
12226: @section Stack depth changes during interpretation
12227: @cindex @file{depth-changes.fs}
12228: @cindex depth changes during interpretation
12229: @cindex stack depth changes during interpretation
12230: @cindex items on the stack after interpretation
12231: 
12232: Sometimes you notice that, after loading a file, there are items left
12233: on the stack.  The tool @file{depth-changes.fs} helps you find out
12234: quickly where in the file these stack items are coming from.
12235: 
12236: The simplest way of using @file{depth-changes.fs} is to include it
12237: before the file(s) you want to check, e.g.:
12238: 
12239: @example
12240: gforth depth-changes.fs my-file.fs
12241: @end example
12242: 
12243: This will compare the stack depths of the data and FP stack at every
12244: empty line (in interpretation state) against these depths at the last
12245: empty line (in interpretation state).  If the depths are not equal,
12246: the position in the file and the stack contents are printed with
12247: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
12248: change has occured in the paragraph of non-empty lines before the
12249: indicated line.  It is a good idea to leave an empty line at the end
12250: of the file, so the last paragraph is checked, too.
12251: 
12252: Checking only at empty lines usually works well, but sometimes you
12253: have big blocks of non-empty lines (e.g., when building a big table),
12254: and you want to know where in this block the stack depth changed.  You
12255: can check all interpreted lines with
12256: 
12257: @example
12258: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12259: @end example
12260: 
12261: This checks the stack depth at every end-of-line.  So the depth change
12262: occured in the line reported by the @code{~~} (not in the line
12263: before).
12264: 
12265: Note that, while this offers better accuracy in indicating where the
12266: stack depth changes, it will often report many intentional stack depth
12267: changes (e.g., when an interpreted computation stretches across
12268: several lines).  You can suppress the checking of some lines by
12269: putting backslashes at the end of these lines (not followed by white
12270: space), and using
12271: 
12272: @example
12273: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12274: @end example
12275: 
12276: @c ******************************************************************
12277: @node ANS conformance, Standard vs Extensions, Tools, Top
12278: @chapter ANS conformance
12279: @cindex ANS conformance of Gforth
12280: 
12281: To the best of our knowledge, Gforth is an
12282: 
12283: ANS Forth System
12284: @itemize @bullet
12285: @item providing the Core Extensions word set
12286: @item providing the Block word set
12287: @item providing the Block Extensions word set
12288: @item providing the Double-Number word set
12289: @item providing the Double-Number Extensions word set
12290: @item providing the Exception word set
12291: @item providing the Exception Extensions word set
12292: @item providing the Facility word set
12293: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12294: @item providing the File Access word set
12295: @item providing the File Access Extensions word set
12296: @item providing the Floating-Point word set
12297: @item providing the Floating-Point Extensions word set
12298: @item providing the Locals word set
12299: @item providing the Locals Extensions word set
12300: @item providing the Memory-Allocation word set
12301: @item providing the Memory-Allocation Extensions word set (that one's easy)
12302: @item providing the Programming-Tools word set
12303: @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
12304: @item providing the Search-Order word set
12305: @item providing the Search-Order Extensions word set
12306: @item providing the String word set
12307: @item providing the String Extensions word set (another easy one)
12308: @end itemize
12309: 
12310: Gforth has the following environmental restrictions:
12311: 
12312: @cindex environmental restrictions
12313: @itemize @bullet
12314: @item
12315: While processing the OS command line, if an exception is not caught,
12316: Gforth exits with a non-zero exit code instyead of performing QUIT.
12317: 
12318: @item
12319: When an @code{throw} is performed after a @code{query}, Gforth does not
12320: allways restore the input source specification in effect at the
12321: corresponding catch.
12322: 
12323: @end itemize
12324: 
12325: 
12326: @cindex system documentation
12327: In addition, ANS Forth systems are required to document certain
12328: implementation choices. This chapter tries to meet these
12329: requirements. In many cases it gives a way to ask the system for the
12330: information instead of providing the information directly, in
12331: particular, if the information depends on the processor, the operating
12332: system or the installation options chosen, or if they are likely to
12333: change during the maintenance of Gforth.
12334: 
12335: @comment The framework for the rest has been taken from pfe.
12336: 
12337: @menu
12338: * The Core Words::              
12339: * The optional Block word set::  
12340: * The optional Double Number word set::  
12341: * The optional Exception word set::  
12342: * The optional Facility word set::  
12343: * The optional File-Access word set::  
12344: * The optional Floating-Point word set::  
12345: * The optional Locals word set::  
12346: * The optional Memory-Allocation word set::  
12347: * The optional Programming-Tools word set::  
12348: * The optional Search-Order word set::  
12349: @end menu
12350: 
12351: 
12352: @c =====================================================================
12353: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12354: @comment  node-name,  next,  previous,  up
12355: @section The Core Words
12356: @c =====================================================================
12357: @cindex core words, system documentation
12358: @cindex system documentation, core words
12359: 
12360: @menu
12361: * core-idef::                   Implementation Defined Options                   
12362: * core-ambcond::                Ambiguous Conditions                
12363: * core-other::                  Other System Documentation                  
12364: @end menu
12365: 
12366: @c ---------------------------------------------------------------------
12367: @node core-idef, core-ambcond, The Core Words, The Core Words
12368: @subsection Implementation Defined Options
12369: @c ---------------------------------------------------------------------
12370: @cindex core words, implementation-defined options
12371: @cindex implementation-defined options, core words
12372: 
12373: 
12374: @table @i
12375: @item (Cell) aligned addresses:
12376: @cindex cell-aligned addresses
12377: @cindex aligned addresses
12378: processor-dependent. Gforth's alignment words perform natural alignment
12379: (e.g., an address aligned for a datum of size 8 is divisible by
12380: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12381: 
12382: @item @code{EMIT} and non-graphic characters:
12383: @cindex @code{EMIT} and non-graphic characters
12384: @cindex non-graphic characters and @code{EMIT}
12385: The character is output using the C library function (actually, macro)
12386: @code{putc}.
12387: 
12388: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12389: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12390: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12391: @cindex @code{ACCEPT}, editing
12392: @cindex @code{EXPECT}, editing
12393: This is modeled on the GNU readline library (@pxref{Readline
12394: Interaction, , Command Line Editing, readline, The GNU Readline
12395: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12396: producing a full word completion every time you type it (instead of
12397: producing the common prefix of all completions). @xref{Command-line editing}.
12398: 
12399: @item character set:
12400: @cindex character set
12401: The character set of your computer and display device. Gforth is
12402: 8-bit-clean (but some other component in your system may make trouble).
12403: 
12404: @item Character-aligned address requirements:
12405: @cindex character-aligned address requirements
12406: installation-dependent. Currently a character is represented by a C
12407: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12408: (Comments on that requested).
12409: 
12410: @item character-set extensions and matching of names:
12411: @cindex character-set extensions and matching of names
12412: @cindex case-sensitivity for name lookup
12413: @cindex name lookup, case-sensitivity
12414: @cindex locale and case-sensitivity
12415: Any character except the ASCII NUL character can be used in a
12416: name. Matching is case-insensitive (except in @code{TABLE}s). The
12417: matching is performed using the C library function @code{strncasecmp}, whose
12418: function is probably influenced by the locale. E.g., the @code{C} locale
12419: does not know about accents and umlauts, so they are matched
12420: case-sensitively in that locale. For portability reasons it is best to
12421: write programs such that they work in the @code{C} locale. Then one can
12422: use libraries written by a Polish programmer (who might use words
12423: containing ISO Latin-2 encoded characters) and by a French programmer
12424: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12425: funny results for some of the words (which ones, depends on the font you
12426: are using)). Also, the locale you prefer may not be available in other
12427: operating systems. Hopefully, Unicode will solve these problems one day.
12428: 
12429: @item conditions under which control characters match a space delimiter:
12430: @cindex space delimiters
12431: @cindex control characters as delimiters
12432: If @code{word} is called with the space character as a delimiter, all
12433: white-space characters (as identified by the C macro @code{isspace()})
12434: are delimiters. @code{Parse}, on the other hand, treats space like other
12435: delimiters.  @code{Parse-name}, which is used by the outer
12436: interpreter (aka text interpreter) by default, treats all white-space
12437: characters as delimiters.
12438: 
12439: @item format of the control-flow stack:
12440: @cindex control-flow stack, format
12441: The data stack is used as control-flow stack. The size of a control-flow
12442: stack item in cells is given by the constant @code{cs-item-size}. At the
12443: time of this writing, an item consists of a (pointer to a) locals list
12444: (third), an address in the code (second), and a tag for identifying the
12445: item (TOS). The following tags are used: @code{defstart},
12446: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12447: @code{scopestart}.
12448: 
12449: @item conversion of digits > 35
12450: @cindex digits > 35
12451: The characters @code{[\]^_'} are the digits with the decimal value
12452: 36@minus{}41. There is no way to input many of the larger digits.
12453: 
12454: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12455: @cindex @code{EXPECT}, display after end of input
12456: @cindex @code{ACCEPT}, display after end of input
12457: The cursor is moved to the end of the entered string. If the input is
12458: terminated using the @kbd{Return} key, a space is typed.
12459: 
12460: @item exception abort sequence of @code{ABORT"}:
12461: @cindex exception abort sequence of @code{ABORT"}
12462: @cindex @code{ABORT"}, exception abort sequence
12463: The error string is stored into the variable @code{"error} and a
12464: @code{-2 throw} is performed.
12465: 
12466: @item input line terminator:
12467: @cindex input line terminator
12468: @cindex line terminator on input
12469: @cindex newline character on input
12470: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12471: lines. One of these characters is typically produced when you type the
12472: @kbd{Enter} or @kbd{Return} key.
12473: 
12474: @item maximum size of a counted string:
12475: @cindex maximum size of a counted string
12476: @cindex counted string, maximum size
12477: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12478: on all platforms, but this may change.
12479: 
12480: @item maximum size of a parsed string:
12481: @cindex maximum size of a parsed string
12482: @cindex parsed string, maximum size
12483: Given by the constant @code{/line}. Currently 255 characters.
12484: 
12485: @item maximum size of a definition name, in characters:
12486: @cindex maximum size of a definition name, in characters
12487: @cindex name, maximum length
12488: MAXU/8
12489: 
12490: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12491: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12492: @cindex @code{ENVIRONMENT?} string length, maximum
12493: MAXU/8
12494: 
12495: @item method of selecting the user input device:
12496: @cindex user input device, method of selecting
12497: The user input device is the standard input. There is currently no way to
12498: change it from within Gforth. However, the input can typically be
12499: redirected in the command line that starts Gforth.
12500: 
12501: @item method of selecting the user output device:
12502: @cindex user output device, method of selecting
12503: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12504: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12505: output when the user output device is a terminal, otherwise the output
12506: is buffered.
12507: 
12508: @item methods of dictionary compilation:
12509: What are we expected to document here?
12510: 
12511: @item number of bits in one address unit:
12512: @cindex number of bits in one address unit
12513: @cindex address unit, size in bits
12514: @code{s" address-units-bits" environment? drop .}. 8 in all current
12515: platforms.
12516: 
12517: @item number representation and arithmetic:
12518: @cindex number representation and arithmetic
12519: Processor-dependent. Binary two's complement on all current platforms.
12520: 
12521: @item ranges for integer types:
12522: @cindex ranges for integer types
12523: @cindex integer types, ranges
12524: Installation-dependent. Make environmental queries for @code{MAX-N},
12525: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12526: unsigned (and positive) types is 0. The lower bound for signed types on
12527: two's complement and one's complement machines machines can be computed
12528: by adding 1 to the upper bound.
12529: 
12530: @item read-only data space regions:
12531: @cindex read-only data space regions
12532: @cindex data-space, read-only regions
12533: The whole Forth data space is writable.
12534: 
12535: @item size of buffer at @code{WORD}:
12536: @cindex size of buffer at @code{WORD}
12537: @cindex @code{WORD} buffer size
12538: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12539: shared with the pictured numeric output string. If overwriting
12540: @code{PAD} is acceptable, it is as large as the remaining dictionary
12541: space, although only as much can be sensibly used as fits in a counted
12542: string.
12543: 
12544: @item size of one cell in address units:
12545: @cindex cell size
12546: @code{1 cells .}.
12547: 
12548: @item size of one character in address units:
12549: @cindex char size
12550: @code{1 chars .}. 1 on all current platforms.
12551: 
12552: @item size of the keyboard terminal buffer:
12553: @cindex size of the keyboard terminal buffer
12554: @cindex terminal buffer, size
12555: Varies. You can determine the size at a specific time using @code{lp@@
12556: tib - .}. It is shared with the locals stack and TIBs of files that
12557: include the current file. You can change the amount of space for TIBs
12558: and locals stack at Gforth startup with the command line option
12559: @code{-l}.
12560: 
12561: @item size of the pictured numeric output buffer:
12562: @cindex size of the pictured numeric output buffer
12563: @cindex pictured numeric output buffer, size
12564: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12565: shared with @code{WORD}.
12566: 
12567: @item size of the scratch area returned by @code{PAD}:
12568: @cindex size of the scratch area returned by @code{PAD}
12569: @cindex @code{PAD} size
12570: The remainder of dictionary space. @code{unused pad here - - .}.
12571: 
12572: @item system case-sensitivity characteristics:
12573: @cindex case-sensitivity characteristics
12574: Dictionary searches are case-insensitive (except in
12575: @code{TABLE}s). However, as explained above under @i{character-set
12576: extensions}, the matching for non-ASCII characters is determined by the
12577: locale you are using. In the default @code{C} locale all non-ASCII
12578: characters are matched case-sensitively.
12579: 
12580: @item system prompt:
12581: @cindex system prompt
12582: @cindex prompt
12583: @code{ ok} in interpret state, @code{ compiled} in compile state.
12584: 
12585: @item division rounding:
12586: @cindex division rounding
12587: installation dependent. @code{s" floored" environment? drop .}. We leave
12588: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12589: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12590: 
12591: @item values of @code{STATE} when true:
12592: @cindex @code{STATE} values
12593: -1.
12594: 
12595: @item values returned after arithmetic overflow:
12596: On two's complement machines, arithmetic is performed modulo
12597: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12598: arithmetic (with appropriate mapping for signed types). Division by zero
12599: typically results in a @code{-55 throw} (Floating-point unidentified
12600: fault) or @code{-10 throw} (divide by zero).
12601: 
12602: @item whether the current definition can be found after @t{DOES>}:
12603: @cindex @t{DOES>}, visibility of current definition
12604: No.
12605: 
12606: @end table
12607: 
12608: @c ---------------------------------------------------------------------
12609: @node core-ambcond, core-other, core-idef, The Core Words
12610: @subsection Ambiguous conditions
12611: @c ---------------------------------------------------------------------
12612: @cindex core words, ambiguous conditions
12613: @cindex ambiguous conditions, core words
12614: 
12615: @table @i
12616: 
12617: @item a name is neither a word nor a number:
12618: @cindex name not found
12619: @cindex undefined word
12620: @code{-13 throw} (Undefined word).
12621: 
12622: @item a definition name exceeds the maximum length allowed:
12623: @cindex word name too long
12624: @code{-19 throw} (Word name too long)
12625: 
12626: @item addressing a region not inside the various data spaces of the forth system:
12627: @cindex Invalid memory address
12628: The stacks, code space and header space are accessible. Machine code space is
12629: typically readable. Accessing other addresses gives results dependent on
12630: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12631: address).
12632: 
12633: @item argument type incompatible with parameter:
12634: @cindex argument type mismatch
12635: This is usually not caught. Some words perform checks, e.g., the control
12636: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12637: mismatch).
12638: 
12639: @item attempting to obtain the execution token of a word with undefined execution semantics:
12640: @cindex Interpreting a compile-only word, for @code{'} etc.
12641: @cindex execution token of words with undefined execution semantics
12642: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12643: get an execution token for @code{compile-only-error} (which performs a
12644: @code{-14 throw} when executed).
12645: 
12646: @item dividing by zero:
12647: @cindex dividing by zero
12648: @cindex floating point unidentified fault, integer division
12649: On some platforms, this produces a @code{-10 throw} (Division by
12650: zero); on other systems, this typically results in a @code{-55 throw}
12651: (Floating-point unidentified fault).
12652: 
12653: @item insufficient data stack or return stack space:
12654: @cindex insufficient data stack or return stack space
12655: @cindex stack overflow
12656: @cindex address alignment exception, stack overflow
12657: @cindex Invalid memory address, stack overflow
12658: Depending on the operating system, the installation, and the invocation
12659: of Gforth, this is either checked by the memory management hardware, or
12660: it is not checked. If it is checked, you typically get a @code{-3 throw}
12661: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12662: throw} (Invalid memory address) (depending on the platform and how you
12663: achieved the overflow) as soon as the overflow happens. If it is not
12664: checked, overflows typically result in mysterious illegal memory
12665: accesses, producing @code{-9 throw} (Invalid memory address) or
12666: @code{-23 throw} (Address alignment exception); they might also destroy
12667: the internal data structure of @code{ALLOCATE} and friends, resulting in
12668: various errors in these words.
12669: 
12670: @item insufficient space for loop control parameters:
12671: @cindex insufficient space for loop control parameters
12672: Like other return stack overflows.
12673: 
12674: @item insufficient space in the dictionary:
12675: @cindex insufficient space in the dictionary
12676: @cindex dictionary overflow
12677: If you try to allot (either directly with @code{allot}, or indirectly
12678: with @code{,}, @code{create} etc.) more memory than available in the
12679: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12680: to access memory beyond the end of the dictionary, the results are
12681: similar to stack overflows.
12682: 
12683: @item interpreting a word with undefined interpretation semantics:
12684: @cindex interpreting a word with undefined interpretation semantics
12685: @cindex Interpreting a compile-only word
12686: For some words, we have defined interpretation semantics. For the
12687: others: @code{-14 throw} (Interpreting a compile-only word).
12688: 
12689: @item modifying the contents of the input buffer or a string literal:
12690: @cindex modifying the contents of the input buffer or a string literal
12691: These are located in writable memory and can be modified.
12692: 
12693: @item overflow of the pictured numeric output string:
12694: @cindex overflow of the pictured numeric output string
12695: @cindex pictured numeric output string, overflow
12696: @code{-17 throw} (Pictured numeric ouput string overflow).
12697: 
12698: @item parsed string overflow:
12699: @cindex parsed string overflow
12700: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12701: 
12702: @item producing a result out of range:
12703: @cindex result out of range
12704: On two's complement machines, arithmetic is performed modulo
12705: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12706: arithmetic (with appropriate mapping for signed types). Division by zero
12707: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12708: throw} (floating point unidentified fault). @code{convert} and
12709: @code{>number} currently overflow silently.
12710: 
12711: @item reading from an empty data or return stack:
12712: @cindex stack empty
12713: @cindex stack underflow
12714: @cindex return stack underflow
12715: The data stack is checked by the outer (aka text) interpreter after
12716: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12717: underflow) is performed. Apart from that, stacks may be checked or not,
12718: depending on operating system, installation, and invocation. If they are
12719: caught by a check, they typically result in @code{-4 throw} (Stack
12720: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12721: (Invalid memory address), depending on the platform and which stack
12722: underflows and by how much. Note that even if the system uses checking
12723: (through the MMU), your program may have to underflow by a significant
12724: number of stack items to trigger the reaction (the reason for this is
12725: that the MMU, and therefore the checking, works with a page-size
12726: granularity).  If there is no checking, the symptoms resulting from an
12727: underflow are similar to those from an overflow.  Unbalanced return
12728: stack errors can result in a variety of symptoms, including @code{-9 throw}
12729: (Invalid memory address) and Illegal Instruction (typically @code{-260
12730: throw}).
12731: 
12732: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12733: @cindex unexpected end of the input buffer
12734: @cindex zero-length string as a name
12735: @cindex Attempt to use zero-length string as a name
12736: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12737: use zero-length string as a name). Words like @code{'} probably will not
12738: find what they search. Note that it is possible to create zero-length
12739: names with @code{nextname} (should it not?).
12740: 
12741: @item @code{>IN} greater than input buffer:
12742: @cindex @code{>IN} greater than input buffer
12743: The next invocation of a parsing word returns a string with length 0.
12744: 
12745: @item @code{RECURSE} appears after @code{DOES>}:
12746: @cindex @code{RECURSE} appears after @code{DOES>}
12747: Compiles a recursive call to the defining word, not to the defined word.
12748: 
12749: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12750: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12751: @cindex argument type mismatch, @code{RESTORE-INPUT}
12752: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12753: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12754: the end of the file was reached), its source-id may be
12755: reused. Therefore, restoring an input source specification referencing a
12756: closed file may lead to unpredictable results instead of a @code{-12
12757: THROW}.
12758: 
12759: In the future, Gforth may be able to restore input source specifications
12760: from other than the current input source.
12761: 
12762: @item data space containing definitions gets de-allocated:
12763: @cindex data space containing definitions gets de-allocated
12764: Deallocation with @code{allot} is not checked. This typically results in
12765: memory access faults or execution of illegal instructions.
12766: 
12767: @item data space read/write with incorrect alignment:
12768: @cindex data space read/write with incorrect alignment
12769: @cindex alignment faults
12770: @cindex address alignment exception
12771: Processor-dependent. Typically results in a @code{-23 throw} (Address
12772: alignment exception). Under Linux-Intel on a 486 or later processor with
12773: alignment turned on, incorrect alignment results in a @code{-9 throw}
12774: (Invalid memory address). There are reportedly some processors with
12775: alignment restrictions that do not report violations.
12776: 
12777: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12778: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12779: Like other alignment errors.
12780: 
12781: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12782: Like other stack underflows.
12783: 
12784: @item loop control parameters not available:
12785: @cindex loop control parameters not available
12786: Not checked. The counted loop words simply assume that the top of return
12787: stack items are loop control parameters and behave accordingly.
12788: 
12789: @item most recent definition does not have a name (@code{IMMEDIATE}):
12790: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12791: @cindex last word was headerless
12792: @code{abort" last word was headerless"}.
12793: 
12794: @item name not defined by @code{VALUE} used by @code{TO}:
12795: @cindex name not defined by @code{VALUE} used by @code{TO}
12796: @cindex @code{TO} on non-@code{VALUE}s
12797: @cindex Invalid name argument, @code{TO}
12798: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12799: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12800: 
12801: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12802: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
12803: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
12804: @code{-13 throw} (Undefined word)
12805: 
12806: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12807: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12808: Gforth behaves as if they were of the same type. I.e., you can predict
12809: the behaviour by interpreting all parameters as, e.g., signed.
12810: 
12811: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12812: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12813: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12814: compilation semantics of @code{TO}.
12815: 
12816: @item String longer than a counted string returned by @code{WORD}:
12817: @cindex string longer than a counted string returned by @code{WORD}
12818: @cindex @code{WORD}, string overflow
12819: Not checked. The string will be ok, but the count will, of course,
12820: contain only the least significant bits of the length.
12821: 
12822: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12823: @cindex @code{LSHIFT}, large shift counts
12824: @cindex @code{RSHIFT}, large shift counts
12825: Processor-dependent. Typical behaviours are returning 0 and using only
12826: the low bits of the shift count.
12827: 
12828: @item word not defined via @code{CREATE}:
12829: @cindex @code{>BODY} of non-@code{CREATE}d words
12830: @code{>BODY} produces the PFA of the word no matter how it was defined.
12831: 
12832: @cindex @code{DOES>} of non-@code{CREATE}d words
12833: @code{DOES>} changes the execution semantics of the last defined word no
12834: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12835: @code{CREATE , DOES>}.
12836: 
12837: @item words improperly used outside @code{<#} and @code{#>}:
12838: Not checked. As usual, you can expect memory faults.
12839: 
12840: @end table
12841: 
12842: 
12843: @c ---------------------------------------------------------------------
12844: @node core-other,  , core-ambcond, The Core Words
12845: @subsection Other system documentation
12846: @c ---------------------------------------------------------------------
12847: @cindex other system documentation, core words
12848: @cindex core words, other system documentation
12849: 
12850: @table @i
12851: @item nonstandard words using @code{PAD}:
12852: @cindex @code{PAD} use by nonstandard words
12853: None.
12854: 
12855: @item operator's terminal facilities available:
12856: @cindex operator's terminal facilities available
12857: After processing the OS's command line, Gforth goes into interactive mode,
12858: and you can give commands to Gforth interactively. The actual facilities
12859: available depend on how you invoke Gforth.
12860: 
12861: @item program data space available:
12862: @cindex program data space available
12863: @cindex data space available
12864: @code{UNUSED .} gives the remaining dictionary space. The total
12865: dictionary space can be specified with the @code{-m} switch
12866: (@pxref{Invoking Gforth}) when Gforth starts up.
12867: 
12868: @item return stack space available:
12869: @cindex return stack space available
12870: You can compute the total return stack space in cells with
12871: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12872: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12873: 
12874: @item stack space available:
12875: @cindex stack space available
12876: You can compute the total data stack space in cells with
12877: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12878: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12879: 
12880: @item system dictionary space required, in address units:
12881: @cindex system dictionary space required, in address units
12882: Type @code{here forthstart - .} after startup. At the time of this
12883: writing, this gives 80080 (bytes) on a 32-bit system.
12884: @end table
12885: 
12886: 
12887: @c =====================================================================
12888: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12889: @section The optional Block word set
12890: @c =====================================================================
12891: @cindex system documentation, block words
12892: @cindex block words, system documentation
12893: 
12894: @menu
12895: * block-idef::                  Implementation Defined Options
12896: * block-ambcond::               Ambiguous Conditions               
12897: * block-other::                 Other System Documentation                 
12898: @end menu
12899: 
12900: 
12901: @c ---------------------------------------------------------------------
12902: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12903: @subsection Implementation Defined Options
12904: @c ---------------------------------------------------------------------
12905: @cindex implementation-defined options, block words
12906: @cindex block words, implementation-defined options
12907: 
12908: @table @i
12909: @item the format for display by @code{LIST}:
12910: @cindex @code{LIST} display format
12911: First the screen number is displayed, then 16 lines of 64 characters,
12912: each line preceded by the line number.
12913: 
12914: @item the length of a line affected by @code{\}:
12915: @cindex length of a line affected by @code{\}
12916: @cindex @code{\}, line length in blocks
12917: 64 characters.
12918: @end table
12919: 
12920: 
12921: @c ---------------------------------------------------------------------
12922: @node block-ambcond, block-other, block-idef, The optional Block word set
12923: @subsection Ambiguous conditions
12924: @c ---------------------------------------------------------------------
12925: @cindex block words, ambiguous conditions
12926: @cindex ambiguous conditions, block words
12927: 
12928: @table @i
12929: @item correct block read was not possible:
12930: @cindex block read not possible
12931: Typically results in a @code{throw} of some OS-derived value (between
12932: -512 and -2048). If the blocks file was just not long enough, blanks are
12933: supplied for the missing portion.
12934: 
12935: @item I/O exception in block transfer:
12936: @cindex I/O exception in block transfer
12937: @cindex block transfer, I/O exception
12938: Typically results in a @code{throw} of some OS-derived value (between
12939: -512 and -2048).
12940: 
12941: @item invalid block number:
12942: @cindex invalid block number
12943: @cindex block number invalid
12944: @code{-35 throw} (Invalid block number)
12945: 
12946: @item a program directly alters the contents of @code{BLK}:
12947: @cindex @code{BLK}, altering @code{BLK}
12948: The input stream is switched to that other block, at the same
12949: position. If the storing to @code{BLK} happens when interpreting
12950: non-block input, the system will get quite confused when the block ends.
12951: 
12952: @item no current block buffer for @code{UPDATE}:
12953: @cindex @code{UPDATE}, no current block buffer
12954: @code{UPDATE} has no effect.
12955: 
12956: @end table
12957: 
12958: @c ---------------------------------------------------------------------
12959: @node block-other,  , block-ambcond, The optional Block word set
12960: @subsection Other system documentation
12961: @c ---------------------------------------------------------------------
12962: @cindex other system documentation, block words
12963: @cindex block words, other system documentation
12964: 
12965: @table @i
12966: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12967: No restrictions (yet).
12968: 
12969: @item the number of blocks available for source and data:
12970: depends on your disk space.
12971: 
12972: @end table
12973: 
12974: 
12975: @c =====================================================================
12976: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12977: @section The optional Double Number word set
12978: @c =====================================================================
12979: @cindex system documentation, double words
12980: @cindex double words, system documentation
12981: 
12982: @menu
12983: * double-ambcond::              Ambiguous Conditions              
12984: @end menu
12985: 
12986: 
12987: @c ---------------------------------------------------------------------
12988: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
12989: @subsection Ambiguous conditions
12990: @c ---------------------------------------------------------------------
12991: @cindex double words, ambiguous conditions
12992: @cindex ambiguous conditions, double words
12993: 
12994: @table @i
12995: @item @i{d} outside of range of @i{n} in @code{D>S}:
12996: @cindex @code{D>S}, @i{d} out of range of @i{n} 
12997: The least significant cell of @i{d} is produced.
12998: 
12999: @end table
13000: 
13001: 
13002: @c =====================================================================
13003: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13004: @section The optional Exception word set
13005: @c =====================================================================
13006: @cindex system documentation, exception words
13007: @cindex exception words, system documentation
13008: 
13009: @menu
13010: * exception-idef::              Implementation Defined Options              
13011: @end menu
13012: 
13013: 
13014: @c ---------------------------------------------------------------------
13015: @node exception-idef,  , The optional Exception word set, The optional Exception word set
13016: @subsection Implementation Defined Options
13017: @c ---------------------------------------------------------------------
13018: @cindex implementation-defined options, exception words
13019: @cindex exception words, implementation-defined options
13020: 
13021: @table @i
13022: @item @code{THROW}-codes used in the system:
13023: @cindex @code{THROW}-codes used in the system
13024: The codes -256@minus{}-511 are used for reporting signals. The mapping
13025: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
13026: codes -512@minus{}-2047 are used for OS errors (for file and memory
13027: allocation operations). The mapping from OS error numbers to throw codes
13028: is -512@minus{}@code{errno}. One side effect of this mapping is that
13029: undefined OS errors produce a message with a strange number; e.g.,
13030: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13031: @end table
13032: 
13033: @c =====================================================================
13034: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13035: @section The optional Facility word set
13036: @c =====================================================================
13037: @cindex system documentation, facility words
13038: @cindex facility words, system documentation
13039: 
13040: @menu
13041: * facility-idef::               Implementation Defined Options               
13042: * facility-ambcond::            Ambiguous Conditions            
13043: @end menu
13044: 
13045: 
13046: @c ---------------------------------------------------------------------
13047: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13048: @subsection Implementation Defined Options
13049: @c ---------------------------------------------------------------------
13050: @cindex implementation-defined options, facility words
13051: @cindex facility words, implementation-defined options
13052: 
13053: @table @i
13054: @item encoding of keyboard events (@code{EKEY}):
13055: @cindex keyboard events, encoding in @code{EKEY}
13056: @cindex @code{EKEY}, encoding of keyboard events
13057: Keys corresponding to ASCII characters are encoded as ASCII characters.
13058: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13059: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13060: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13061: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
13062: 
13063: 
13064: @item duration of a system clock tick:
13065: @cindex duration of a system clock tick
13066: @cindex clock tick duration
13067: System dependent. With respect to @code{MS}, the time is specified in
13068: microseconds. How well the OS and the hardware implement this, is
13069: another question.
13070: 
13071: @item repeatability to be expected from the execution of @code{MS}:
13072: @cindex repeatability to be expected from the execution of @code{MS}
13073: @cindex @code{MS}, repeatability to be expected
13074: System dependent. On Unix, a lot depends on load. If the system is
13075: lightly loaded, and the delay is short enough that Gforth does not get
13076: swapped out, the performance should be acceptable. Under MS-DOS and
13077: other single-tasking systems, it should be good.
13078: 
13079: @end table
13080: 
13081: 
13082: @c ---------------------------------------------------------------------
13083: @node facility-ambcond,  , facility-idef, The optional Facility word set
13084: @subsection Ambiguous conditions
13085: @c ---------------------------------------------------------------------
13086: @cindex facility words, ambiguous conditions
13087: @cindex ambiguous conditions, facility words
13088: 
13089: @table @i
13090: @item @code{AT-XY} can't be performed on user output device:
13091: @cindex @code{AT-XY} can't be performed on user output device
13092: Largely terminal dependent. No range checks are done on the arguments.
13093: No errors are reported. You may see some garbage appearing, you may see
13094: simply nothing happen.
13095: 
13096: @end table
13097: 
13098: 
13099: @c =====================================================================
13100: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13101: @section The optional File-Access word set
13102: @c =====================================================================
13103: @cindex system documentation, file words
13104: @cindex file words, system documentation
13105: 
13106: @menu
13107: * file-idef::                   Implementation Defined Options
13108: * file-ambcond::                Ambiguous Conditions                
13109: @end menu
13110: 
13111: @c ---------------------------------------------------------------------
13112: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13113: @subsection Implementation Defined Options
13114: @c ---------------------------------------------------------------------
13115: @cindex implementation-defined options, file words
13116: @cindex file words, implementation-defined options
13117: 
13118: @table @i
13119: @item file access methods used:
13120: @cindex file access methods used
13121: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13122: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13123: @code{wb}): The file is cleared, if it exists, and created, if it does
13124: not (with both @code{open-file} and @code{create-file}).  Under Unix
13125: @code{create-file} creates a file with 666 permissions modified by your
13126: umask.
13127: 
13128: @item file exceptions:
13129: @cindex file exceptions
13130: The file words do not raise exceptions (except, perhaps, memory access
13131: faults when you pass illegal addresses or file-ids).
13132: 
13133: @item file line terminator:
13134: @cindex file line terminator
13135: System-dependent. Gforth uses C's newline character as line
13136: terminator. What the actual character code(s) of this are is
13137: system-dependent.
13138: 
13139: @item file name format:
13140: @cindex file name format
13141: System dependent. Gforth just uses the file name format of your OS.
13142: 
13143: @item information returned by @code{FILE-STATUS}:
13144: @cindex @code{FILE-STATUS}, returned information
13145: @code{FILE-STATUS} returns the most powerful file access mode allowed
13146: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13147: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13148: along with the returned mode.
13149: 
13150: @item input file state after an exception when including source:
13151: @cindex exception when including source
13152: All files that are left via the exception are closed.
13153: 
13154: @item @i{ior} values and meaning:
13155: @cindex @i{ior} values and meaning
13156: @cindex @i{wior} values and meaning
13157: The @i{ior}s returned by the file and memory allocation words are
13158: intended as throw codes. They typically are in the range
13159: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13160: @i{ior}s is -512@minus{}@i{errno}.
13161: 
13162: @item maximum depth of file input nesting:
13163: @cindex maximum depth of file input nesting
13164: @cindex file input nesting, maximum depth
13165: limited by the amount of return stack, locals/TIB stack, and the number
13166: of open files available. This should not give you troubles.
13167: 
13168: @item maximum size of input line:
13169: @cindex maximum size of input line
13170: @cindex input line size, maximum
13171: @code{/line}. Currently 255.
13172: 
13173: @item methods of mapping block ranges to files:
13174: @cindex mapping block ranges to files
13175: @cindex files containing blocks
13176: @cindex blocks in files
13177: By default, blocks are accessed in the file @file{blocks.fb} in the
13178: current working directory. The file can be switched with @code{USE}.
13179: 
13180: @item number of string buffers provided by @code{S"}:
13181: @cindex @code{S"}, number of string buffers
13182: 1
13183: 
13184: @item size of string buffer used by @code{S"}:
13185: @cindex @code{S"}, size of string buffer
13186: @code{/line}. currently 255.
13187: 
13188: @end table
13189: 
13190: @c ---------------------------------------------------------------------
13191: @node file-ambcond,  , file-idef, The optional File-Access word set
13192: @subsection Ambiguous conditions
13193: @c ---------------------------------------------------------------------
13194: @cindex file words, ambiguous conditions
13195: @cindex ambiguous conditions, file words
13196: 
13197: @table @i
13198: @item attempting to position a file outside its boundaries:
13199: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13200: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13201: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13202: 
13203: @item attempting to read from file positions not yet written:
13204: @cindex reading from file positions not yet written
13205: End-of-file, i.e., zero characters are read and no error is reported.
13206: 
13207: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13208: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
13209: An appropriate exception may be thrown, but a memory fault or other
13210: problem is more probable.
13211: 
13212: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13213: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13214: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13215: The @i{ior} produced by the operation, that discovered the problem, is
13216: thrown.
13217: 
13218: @item named file cannot be opened (@code{INCLUDED}):
13219: @cindex @code{INCLUDED}, named file cannot be opened
13220: The @i{ior} produced by @code{open-file} is thrown.
13221: 
13222: @item requesting an unmapped block number:
13223: @cindex unmapped block numbers
13224: There are no unmapped legal block numbers. On some operating systems,
13225: writing a block with a large number may overflow the file system and
13226: have an error message as consequence.
13227: 
13228: @item using @code{source-id} when @code{blk} is non-zero:
13229: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13230: @code{source-id} performs its function. Typically it will give the id of
13231: the source which loaded the block. (Better ideas?)
13232: 
13233: @end table
13234: 
13235: 
13236: @c =====================================================================
13237: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13238: @section The optional Floating-Point word set
13239: @c =====================================================================
13240: @cindex system documentation, floating-point words
13241: @cindex floating-point words, system documentation
13242: 
13243: @menu
13244: * floating-idef::               Implementation Defined Options
13245: * floating-ambcond::            Ambiguous Conditions            
13246: @end menu
13247: 
13248: 
13249: @c ---------------------------------------------------------------------
13250: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13251: @subsection Implementation Defined Options
13252: @c ---------------------------------------------------------------------
13253: @cindex implementation-defined options, floating-point words
13254: @cindex floating-point words, implementation-defined options
13255: 
13256: @table @i
13257: @item format and range of floating point numbers:
13258: @cindex format and range of floating point numbers
13259: @cindex floating point numbers, format and range
13260: System-dependent; the @code{double} type of C.
13261: 
13262: @item results of @code{REPRESENT} when @i{float} is out of range:
13263: @cindex  @code{REPRESENT}, results when @i{float} is out of range
13264: System dependent; @code{REPRESENT} is implemented using the C library
13265: function @code{ecvt()} and inherits its behaviour in this respect.
13266: 
13267: @item rounding or truncation of floating-point numbers:
13268: @cindex rounding of floating-point numbers
13269: @cindex truncation of floating-point numbers
13270: @cindex floating-point numbers, rounding or truncation
13271: System dependent; the rounding behaviour is inherited from the hosting C
13272: compiler. IEEE-FP-based (i.e., most) systems by default round to
13273: nearest, and break ties by rounding to even (i.e., such that the last
13274: bit of the mantissa is 0).
13275: 
13276: @item size of floating-point stack:
13277: @cindex floating-point stack size
13278: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13279: the floating-point stack (in floats). You can specify this on startup
13280: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13281: 
13282: @item width of floating-point stack:
13283: @cindex floating-point stack width 
13284: @code{1 floats}.
13285: 
13286: @end table
13287: 
13288: 
13289: @c ---------------------------------------------------------------------
13290: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
13291: @subsection Ambiguous conditions
13292: @c ---------------------------------------------------------------------
13293: @cindex floating-point words, ambiguous conditions
13294: @cindex ambiguous conditions, floating-point words
13295: 
13296: @table @i
13297: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
13298: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
13299: System-dependent. Typically results in a @code{-23 THROW} like other
13300: alignment violations.
13301: 
13302: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
13303: @cindex @code{f@@} used with an address that is not float aligned
13304: @cindex @code{f!} used with an address that is not float aligned
13305: System-dependent. Typically results in a @code{-23 THROW} like other
13306: alignment violations.
13307: 
13308: @item floating-point result out of range:
13309: @cindex floating-point result out of range
13310: System-dependent. Can result in a @code{-43 throw} (floating point
13311: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13312: (floating point inexact result), @code{-55 THROW} (Floating-point
13313: unidentified fault), or can produce a special value representing, e.g.,
13314: Infinity.
13315: 
13316: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
13317: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
13318: System-dependent. Typically results in an alignment fault like other
13319: alignment violations.
13320: 
13321: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13322: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13323: The floating-point number is converted into decimal nonetheless.
13324: 
13325: @item Both arguments are equal to zero (@code{FATAN2}):
13326: @cindex @code{FATAN2}, both arguments are equal to zero
13327: System-dependent. @code{FATAN2} is implemented using the C library
13328: function @code{atan2()}.
13329: 
13330: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13331: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13332: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13333: because of small errors and the tan will be a very large (or very small)
13334: but finite number.
13335: 
13336: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13337: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13338: The result is rounded to the nearest float.
13339: 
13340: @item dividing by zero:
13341: @cindex dividing by zero, floating-point
13342: @cindex floating-point dividing by zero
13343: @cindex floating-point unidentified fault, FP divide-by-zero
13344: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13345: (floating point divide by zero) or @code{-55 throw} (Floating-point
13346: unidentified fault).
13347: 
13348: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13349: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13350: System dependent. On IEEE-FP based systems the number is converted into
13351: an infinity.
13352: 
13353: @item @i{float}<1 (@code{FACOSH}):
13354: @cindex @code{FACOSH}, @i{float}<1
13355: @cindex floating-point unidentified fault, @code{FACOSH}
13356: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13357: 
13358: @item @i{float}=<-1 (@code{FLNP1}):
13359: @cindex @code{FLNP1}, @i{float}=<-1
13360: @cindex floating-point unidentified fault, @code{FLNP1}
13361: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13362: negative infinity for @i{float}=-1).
13363: 
13364: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13365: @cindex @code{FLN}, @i{float}=<0
13366: @cindex @code{FLOG}, @i{float}=<0
13367: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13368: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13369: negative infinity for @i{float}=0).
13370: 
13371: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13372: @cindex @code{FASINH}, @i{float}<0
13373: @cindex @code{FSQRT}, @i{float}<0
13374: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13375: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13376: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13377: C library?).
13378: 
13379: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13380: @cindex @code{FACOS}, |@i{float}|>1
13381: @cindex @code{FASIN}, |@i{float}|>1
13382: @cindex @code{FATANH}, |@i{float}|>1
13383: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13384: Platform-dependent; IEEE-FP systems typically produce a NaN.
13385: 
13386: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13387: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13388: @cindex floating-point unidentified fault, @code{F>D}
13389: Platform-dependent; typically, some double number is produced and no
13390: error is reported.
13391: 
13392: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13393: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13394: @code{Precision} characters of the numeric output area are used.  If
13395: @code{precision} is too high, these words will smash the data or code
13396: close to @code{here}.
13397: @end table
13398: 
13399: @c =====================================================================
13400: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13401: @section The optional Locals word set
13402: @c =====================================================================
13403: @cindex system documentation, locals words
13404: @cindex locals words, system documentation
13405: 
13406: @menu
13407: * locals-idef::                 Implementation Defined Options                 
13408: * locals-ambcond::              Ambiguous Conditions              
13409: @end menu
13410: 
13411: 
13412: @c ---------------------------------------------------------------------
13413: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13414: @subsection Implementation Defined Options
13415: @c ---------------------------------------------------------------------
13416: @cindex implementation-defined options, locals words
13417: @cindex locals words, implementation-defined options
13418: 
13419: @table @i
13420: @item maximum number of locals in a definition:
13421: @cindex maximum number of locals in a definition
13422: @cindex locals, maximum number in a definition
13423: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13424: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13425: characters. The number of locals in a definition is bounded by the size
13426: of locals-buffer, which contains the names of the locals.
13427: 
13428: @end table
13429: 
13430: 
13431: @c ---------------------------------------------------------------------
13432: @node locals-ambcond,  , locals-idef, The optional Locals word set
13433: @subsection Ambiguous conditions
13434: @c ---------------------------------------------------------------------
13435: @cindex locals words, ambiguous conditions
13436: @cindex ambiguous conditions, locals words
13437: 
13438: @table @i
13439: @item executing a named local in interpretation state:
13440: @cindex local in interpretation state
13441: @cindex Interpreting a compile-only word, for a local
13442: Locals have no interpretation semantics. If you try to perform the
13443: interpretation semantics, you will get a @code{-14 throw} somewhere
13444: (Interpreting a compile-only word). If you perform the compilation
13445: semantics, the locals access will be compiled (irrespective of state).
13446: 
13447: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13448: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13449: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13450: @cindex Invalid name argument, @code{TO}
13451: @code{-32 throw} (Invalid name argument)
13452: 
13453: @end table
13454: 
13455: 
13456: @c =====================================================================
13457: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13458: @section The optional Memory-Allocation word set
13459: @c =====================================================================
13460: @cindex system documentation, memory-allocation words
13461: @cindex memory-allocation words, system documentation
13462: 
13463: @menu
13464: * memory-idef::                 Implementation Defined Options                 
13465: @end menu
13466: 
13467: 
13468: @c ---------------------------------------------------------------------
13469: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13470: @subsection Implementation Defined Options
13471: @c ---------------------------------------------------------------------
13472: @cindex implementation-defined options, memory-allocation words
13473: @cindex memory-allocation words, implementation-defined options
13474: 
13475: @table @i
13476: @item values and meaning of @i{ior}:
13477: @cindex  @i{ior} values and meaning
13478: The @i{ior}s returned by the file and memory allocation words are
13479: intended as throw codes. They typically are in the range
13480: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13481: @i{ior}s is -512@minus{}@i{errno}.
13482: 
13483: @end table
13484: 
13485: @c =====================================================================
13486: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13487: @section The optional Programming-Tools word set
13488: @c =====================================================================
13489: @cindex system documentation, programming-tools words
13490: @cindex programming-tools words, system documentation
13491: 
13492: @menu
13493: * programming-idef::            Implementation Defined Options            
13494: * programming-ambcond::         Ambiguous Conditions         
13495: @end menu
13496: 
13497: 
13498: @c ---------------------------------------------------------------------
13499: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13500: @subsection Implementation Defined Options
13501: @c ---------------------------------------------------------------------
13502: @cindex implementation-defined options, programming-tools words
13503: @cindex programming-tools words, implementation-defined options
13504: 
13505: @table @i
13506: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13507: @cindex @code{;CODE} ending sequence
13508: @cindex @code{CODE} ending sequence
13509: @code{END-CODE}
13510: 
13511: @item manner of processing input following @code{;CODE} and @code{CODE}:
13512: @cindex @code{;CODE}, processing input
13513: @cindex @code{CODE}, processing input
13514: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13515: the input is processed by the text interpreter, (starting) in interpret
13516: state.
13517: 
13518: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13519: @cindex @code{ASSEMBLER}, search order capability
13520: The ANS Forth search order word set.
13521: 
13522: @item source and format of display by @code{SEE}:
13523: @cindex @code{SEE}, source and format of output
13524: The source for @code{see} is the executable code used by the inner
13525: interpreter.  The current @code{see} tries to output Forth source code
13526: (and on some platforms, assembly code for primitives) as well as
13527: possible.
13528: 
13529: @end table
13530: 
13531: @c ---------------------------------------------------------------------
13532: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
13533: @subsection Ambiguous conditions
13534: @c ---------------------------------------------------------------------
13535: @cindex programming-tools words, ambiguous conditions
13536: @cindex ambiguous conditions, programming-tools words
13537: 
13538: @table @i
13539: 
13540: @item deleting the compilation word list (@code{FORGET}):
13541: @cindex @code{FORGET}, deleting the compilation word list
13542: Not implemented (yet).
13543: 
13544: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13545: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13546: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13547: @cindex control-flow stack underflow
13548: This typically results in an @code{abort"} with a descriptive error
13549: message (may change into a @code{-22 throw} (Control structure mismatch)
13550: in the future). You may also get a memory access error. If you are
13551: unlucky, this ambiguous condition is not caught.
13552: 
13553: @item @i{name} can't be found (@code{FORGET}):
13554: @cindex @code{FORGET}, @i{name} can't be found
13555: Not implemented (yet).
13556: 
13557: @item @i{name} not defined via @code{CREATE}:
13558: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13559: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13560: the execution semantics of the last defined word no matter how it was
13561: defined.
13562: 
13563: @item @code{POSTPONE} applied to @code{[IF]}:
13564: @cindex @code{POSTPONE} applied to @code{[IF]}
13565: @cindex @code{[IF]} and @code{POSTPONE}
13566: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13567: equivalent to @code{[IF]}.
13568: 
13569: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13570: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13571: Continue in the same state of conditional compilation in the next outer
13572: input source. Currently there is no warning to the user about this.
13573: 
13574: @item removing a needed definition (@code{FORGET}):
13575: @cindex @code{FORGET}, removing a needed definition
13576: Not implemented (yet).
13577: 
13578: @end table
13579: 
13580: 
13581: @c =====================================================================
13582: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
13583: @section The optional Search-Order word set
13584: @c =====================================================================
13585: @cindex system documentation, search-order words
13586: @cindex search-order words, system documentation
13587: 
13588: @menu
13589: * search-idef::                 Implementation Defined Options                 
13590: * search-ambcond::              Ambiguous Conditions              
13591: @end menu
13592: 
13593: 
13594: @c ---------------------------------------------------------------------
13595: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13596: @subsection Implementation Defined Options
13597: @c ---------------------------------------------------------------------
13598: @cindex implementation-defined options, search-order words
13599: @cindex search-order words, implementation-defined options
13600: 
13601: @table @i
13602: @item maximum number of word lists in search order:
13603: @cindex maximum number of word lists in search order
13604: @cindex search order, maximum depth
13605: @code{s" wordlists" environment? drop .}. Currently 16.
13606: 
13607: @item minimum search order:
13608: @cindex minimum search order
13609: @cindex search order, minimum
13610: @code{root root}.
13611: 
13612: @end table
13613: 
13614: @c ---------------------------------------------------------------------
13615: @node search-ambcond,  , search-idef, The optional Search-Order word set
13616: @subsection Ambiguous conditions
13617: @c ---------------------------------------------------------------------
13618: @cindex search-order words, ambiguous conditions
13619: @cindex ambiguous conditions, search-order words
13620: 
13621: @table @i
13622: @item changing the compilation word list (during compilation):
13623: @cindex changing the compilation word list (during compilation)
13624: @cindex compilation word list, change before definition ends
13625: The word is entered into the word list that was the compilation word list
13626: at the start of the definition. Any changes to the name field (e.g.,
13627: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13628: are applied to the latest defined word (as reported by @code{latest} or
13629: @code{latestxt}), if possible, irrespective of the compilation word list.
13630: 
13631: @item search order empty (@code{previous}):
13632: @cindex @code{previous}, search order empty
13633: @cindex vocstack empty, @code{previous}
13634: @code{abort" Vocstack empty"}.
13635: 
13636: @item too many word lists in search order (@code{also}):
13637: @cindex @code{also}, too many word lists in search order
13638: @cindex vocstack full, @code{also}
13639: @code{abort" Vocstack full"}.
13640: 
13641: @end table
13642: 
13643: @c ***************************************************************
13644: @node Standard vs Extensions, Model, ANS conformance, Top
13645: @chapter Should I use Gforth extensions?
13646: @cindex Gforth extensions
13647: 
13648: As you read through the rest of this manual, you will see documentation
13649: for @i{Standard} words, and documentation for some appealing Gforth
13650: @i{extensions}. You might ask yourself the question: @i{``Should I
13651: restrict myself to the standard, or should I use the extensions?''}
13652: 
13653: The answer depends on the goals you have for the program you are working
13654: on:
13655: 
13656: @itemize @bullet
13657: 
13658: @item Is it just for yourself or do you want to share it with others?
13659: 
13660: @item
13661: If you want to share it, do the others all use Gforth?
13662: 
13663: @item
13664: If it is just for yourself, do you want to restrict yourself to Gforth?
13665: 
13666: @end itemize
13667: 
13668: If restricting the program to Gforth is ok, then there is no reason not
13669: to use extensions.  It is still a good idea to keep to the standard
13670: where it is easy, in case you want to reuse these parts in another
13671: program that you want to be portable.
13672: 
13673: If you want to be able to port the program to other Forth systems, there
13674: are the following points to consider:
13675: 
13676: @itemize @bullet
13677: 
13678: @item
13679: Most Forth systems that are being maintained support the ANS Forth
13680: standard.  So if your program complies with the standard, it will be
13681: portable among many systems.
13682: 
13683: @item
13684: A number of the Gforth extensions can be implemented in ANS Forth using
13685: public-domain files provided in the @file{compat/} directory. These are
13686: mentioned in the text in passing.  There is no reason not to use these
13687: extensions, your program will still be ANS Forth compliant; just include
13688: the appropriate compat files with your program.
13689: 
13690: @item
13691: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13692: analyse your program and determine what non-Standard words it relies
13693: upon.  However, it does not check whether you use standard words in a
13694: non-standard way.
13695: 
13696: @item
13697: Some techniques are not standardized by ANS Forth, and are hard or
13698: impossible to implement in a standard way, but can be implemented in
13699: most Forth systems easily, and usually in similar ways (e.g., accessing
13700: word headers).  Forth has a rich historical precedent for programmers
13701: taking advantage of implementation-dependent features of their tools
13702: (for example, relying on a knowledge of the dictionary
13703: structure). Sometimes these techniques are necessary to extract every
13704: last bit of performance from the hardware, sometimes they are just a
13705: programming shorthand.
13706: 
13707: @item
13708: Does using a Gforth extension save more work than the porting this part
13709: to other Forth systems (if any) will cost?
13710: 
13711: @item
13712: Is the additional functionality worth the reduction in portability and
13713: the additional porting problems?
13714: 
13715: @end itemize
13716: 
13717: In order to perform these consideratios, you need to know what's
13718: standard and what's not.  This manual generally states if something is
13719: non-standard, but the authoritative source is the
13720: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
13721: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13722: into the thought processes of the technical committee.
13723: 
13724: Note also that portability between Forth systems is not the only
13725: portability issue; there is also the issue of portability between
13726: different platforms (processor/OS combinations).
13727: 
13728: @c ***************************************************************
13729: @node Model, Integrating Gforth, Standard vs Extensions, Top
13730: @chapter Model
13731: 
13732: This chapter has yet to be written. It will contain information, on
13733: which internal structures you can rely.
13734: 
13735: @c ***************************************************************
13736: @node Integrating Gforth, Emacs and Gforth, Model, Top
13737: @chapter Integrating Gforth into C programs
13738: 
13739: This is not yet implemented.
13740: 
13741: Several people like to use Forth as scripting language for applications
13742: that are otherwise written in C, C++, or some other language.
13743: 
13744: The Forth system ATLAST provides facilities for embedding it into
13745: applications; unfortunately it has several disadvantages: most
13746: importantly, it is not based on ANS Forth, and it is apparently dead
13747: (i.e., not developed further and not supported). The facilities
13748: provided by Gforth in this area are inspired by ATLAST's facilities, so
13749: making the switch should not be hard.
13750: 
13751: We also tried to design the interface such that it can easily be
13752: implemented by other Forth systems, so that we may one day arrive at a
13753: standardized interface. Such a standard interface would allow you to
13754: replace the Forth system without having to rewrite C code.
13755: 
13756: You embed the Gforth interpreter by linking with the library
13757: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
13758: global symbols in this library that belong to the interface, have the
13759: prefix @code{forth_}. (Global symbols that are used internally have the
13760: prefix @code{gforth_}).
13761: 
13762: You can include the declarations of Forth types and the functions and
13763: variables of the interface with @code{#include <forth.h>}.
13764: 
13765: Types.
13766: 
13767: Variables.
13768: 
13769: Data and FP Stack pointer. Area sizes.
13770: 
13771: functions.
13772: 
13773: forth_init(imagefile)
13774: forth_evaluate(string) exceptions?
13775: forth_goto(address) (or forth_execute(xt)?)
13776: forth_continue() (a corountining mechanism)
13777: 
13778: Adding primitives.
13779: 
13780: No checking.
13781: 
13782: Signals?
13783: 
13784: Accessing the Stacks
13785: 
13786: @c ******************************************************************
13787: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13788: @chapter Emacs and Gforth
13789: @cindex Emacs and Gforth
13790: 
13791: @cindex @file{gforth.el}
13792: @cindex @file{forth.el}
13793: @cindex Rydqvist, Goran
13794: @cindex Kuehling, David
13795: @cindex comment editing commands
13796: @cindex @code{\}, editing with Emacs
13797: @cindex debug tracer editing commands
13798: @cindex @code{~~}, removal with Emacs
13799: @cindex Forth mode in Emacs
13800: 
13801: Gforth comes with @file{gforth.el}, an improved version of
13802: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
13803: improvements are:
13804: 
13805: @itemize @bullet
13806: @item
13807: A better handling of indentation.
13808: @item
13809: A custom hilighting engine for Forth-code.
13810: @item
13811: Comment paragraph filling (@kbd{M-q})
13812: @item
13813: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13814: @item
13815: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
13816: @item
13817: Support of the @code{info-lookup} feature for looking up the
13818: documentation of a word.
13819: @item
13820: Support for reading and writing blocks files.
13821: @end itemize
13822: 
13823: To get a basic description of these features, enter Forth mode and
13824: type @kbd{C-h m}.
13825: 
13826: @cindex source location of error or debugging output in Emacs
13827: @cindex error output, finding the source location in Emacs
13828: @cindex debugging output, finding the source location in Emacs
13829: In addition, Gforth supports Emacs quite well: The source code locations
13830: given in error messages, debugging output (from @code{~~}) and failed
13831: assertion messages are in the right format for Emacs' compilation mode
13832: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13833: Manual}) so the source location corresponding to an error or other
13834: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13835: @kbd{C-c C-c} for the error under the cursor).
13836: 
13837: @cindex viewing the documentation of a word in Emacs
13838: @cindex context-sensitive help
13839: Moreover, for words documented in this manual, you can look up the
13840: glossary entry quickly by using @kbd{C-h TAB}
13841: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13842: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
13843: later and does not work for words containing @code{:}.
13844: 
13845: @menu
13846: * Installing gforth.el::        Making Emacs aware of Forth.
13847: * Emacs Tags::                  Viewing the source of a word in Emacs.
13848: * Hilighting::                  Making Forth code look prettier.
13849: * Auto-Indentation::            Customizing auto-indentation.
13850: * Blocks Files::                Reading and writing blocks files.
13851: @end menu
13852: 
13853: @c ----------------------------------
13854: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
13855: @section Installing gforth.el
13856: @cindex @file{.emacs}
13857: @cindex @file{gforth.el}, installation
13858: To make the features from @file{gforth.el} available in Emacs, add
13859: the following lines to your @file{.emacs} file:
13860: 
13861: @example
13862: (autoload 'forth-mode "gforth.el")
13863: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
13864: 			    auto-mode-alist))
13865: (autoload 'forth-block-mode "gforth.el")
13866: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
13867: 			    auto-mode-alist))
13868: (add-hook 'forth-mode-hook (function (lambda ()
13869:    ;; customize variables here:
13870:    (setq forth-indent-level 4)
13871:    (setq forth-minor-indent-level 2)
13872:    (setq forth-hilight-level 3)
13873:    ;;; ...
13874: )))
13875: @end example
13876: 
13877: @c ----------------------------------
13878: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13879: @section Emacs Tags
13880: @cindex @file{TAGS} file
13881: @cindex @file{etags.fs}
13882: @cindex viewing the source of a word in Emacs
13883: @cindex @code{require}, placement in files
13884: @cindex @code{include}, placement in files
13885: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13886: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
13887: contains the definitions of all words defined afterwards. You can then
13888: find the source for a word using @kbd{M-.}. Note that Emacs can use
13889: several tags files at the same time (e.g., one for the Gforth sources
13890: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13891: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13892: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
13893: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
13894: with @file{etags.fs}, you should avoid putting definitions both before
13895: and after @code{require} etc., otherwise you will see the same file
13896: visited several times by commands like @code{tags-search}.
13897: 
13898: @c ----------------------------------
13899: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13900: @section Hilighting
13901: @cindex hilighting Forth code in Emacs
13902: @cindex highlighting Forth code in Emacs
13903: @file{gforth.el} comes with a custom source hilighting engine.  When
13904: you open a file in @code{forth-mode}, it will be completely parsed,
13905: assigning faces to keywords, comments, strings etc.  While you edit
13906: the file, modified regions get parsed and updated on-the-fly. 
13907: 
13908: Use the variable `forth-hilight-level' to change the level of
13909: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
13910: you set the hilighting level to 0, the parser will still work in the
13911: background, collecting information about whether regions of text are
13912: ``compiled'' or ``interpreted''.  Those information are required for
13913: auto-indentation to work properly.  Set `forth-disable-parser' to
13914: non-nil if your computer is too slow to handle parsing.  This will
13915: have an impact on the smartness of the auto-indentation engine,
13916: though.
13917: 
13918: Sometimes Forth sources define new features that should be hilighted,
13919: new control structures, defining-words etc.  You can use the variable
13920: `forth-custom-words' to make @code{forth-mode} hilight additional
13921: words and constructs.  See the docstring of `forth-words' for details
13922: (in Emacs, type @kbd{C-h v forth-words}).
13923: 
13924: `forth-custom-words' is meant to be customized in your
13925: @file{.emacs} file.  To customize hilighing in a file-specific manner,
13926: set `forth-local-words' in a local-variables section at the end of
13927: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13928: 
13929: Example:
13930: @example
13931: 0 [IF]
13932:    Local Variables:
13933:    forth-local-words:
13934:       ((("t:") definition-starter (font-lock-keyword-face . 1)
13935:         "[ \t\n]" t name (font-lock-function-name-face . 3))
13936:        ((";t") definition-ender (font-lock-keyword-face . 1)))
13937:    End:
13938: [THEN]
13939: @end example
13940: 
13941: @c ----------------------------------
13942: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13943: @section Auto-Indentation
13944: @cindex auto-indentation of Forth code in Emacs
13945: @cindex indentation of Forth code in Emacs
13946: @code{forth-mode} automatically tries to indent lines in a smart way,
13947: whenever you type @key{TAB} or break a line with @kbd{C-m}.
13948: 
13949: Simple customization can be achieved by setting
13950: `forth-indent-level' and `forth-minor-indent-level' in your
13951: @file{.emacs} file. For historical reasons @file{gforth.el} indents
13952: per default by multiples of 4 columns.  To use the more traditional
13953: 3-column indentation, add the following lines to your @file{.emacs}:
13954: 
13955: @example
13956: (add-hook 'forth-mode-hook (function (lambda ()
13957:    ;; customize variables here:
13958:    (setq forth-indent-level 3)
13959:    (setq forth-minor-indent-level 1)
13960: )))
13961: @end example
13962: 
13963: If you want indentation to recognize non-default words, customize it
13964: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
13965: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
13966: v forth-indent-words}).
13967: 
13968: To customize indentation in a file-specific manner, set
13969: `forth-local-indent-words' in a local-variables section at the end of
13970: your source file (@pxref{Local Variables in Files, Variables,,emacs,
13971: Emacs Manual}).
13972: 
13973: Example:
13974: @example
13975: 0 [IF]
13976:    Local Variables:
13977:    forth-local-indent-words:
13978:       ((("t:") (0 . 2) (0 . 2))
13979:        ((";t") (-2 . 0) (0 . -2)))
13980:    End:
13981: [THEN]
13982: @end example
13983: 
13984: @c ----------------------------------
13985: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
13986: @section Blocks Files
13987: @cindex blocks files, use with Emacs
13988: @code{forth-mode} Autodetects blocks files by checking whether the
13989: length of the first line exceeds 1023 characters.  It then tries to
13990: convert the file into normal text format.  When you save the file, it
13991: will be written to disk as normal stream-source file.
13992: 
13993: If you want to write blocks files, use @code{forth-blocks-mode}.  It
13994: inherits all the features from @code{forth-mode}, plus some additions:
13995: 
13996: @itemize @bullet
13997: @item
13998: Files are written to disk in blocks file format.
13999: @item
14000: Screen numbers are displayed in the mode line (enumerated beginning
14001: with the value of `forth-block-base')
14002: @item
14003: Warnings are displayed when lines exceed 64 characters.
14004: @item
14005: The beginning of the currently edited block is marked with an
14006: overlay-arrow. 
14007: @end itemize
14008: 
14009: There are some restrictions you should be aware of.  When you open a
14010: blocks file that contains tabulator or newline characters, these
14011: characters will be translated into spaces when the file is written
14012: back to disk.  If tabs or newlines are encountered during blocks file
14013: reading, an error is output to the echo area. So have a look at the
14014: `*Messages*' buffer, when Emacs' bell rings during reading.
14015: 
14016: Please consult the docstring of @code{forth-blocks-mode} for more
14017: information by typing @kbd{C-h v forth-blocks-mode}).
14018: 
14019: @c ******************************************************************
14020: @node Image Files, Engine, Emacs and Gforth, Top
14021: @chapter Image Files
14022: @cindex image file
14023: @cindex @file{.fi} files
14024: @cindex precompiled Forth code
14025: @cindex dictionary in persistent form
14026: @cindex persistent form of dictionary
14027: 
14028: An image file is a file containing an image of the Forth dictionary,
14029: i.e., compiled Forth code and data residing in the dictionary.  By
14030: convention, we use the extension @code{.fi} for image files.
14031: 
14032: @menu
14033: * Image Licensing Issues::      Distribution terms for images.
14034: * Image File Background::       Why have image files?
14035: * Non-Relocatable Image Files::  don't always work.
14036: * Data-Relocatable Image Files::  are better.
14037: * Fully Relocatable Image Files::  better yet.
14038: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
14039: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
14040: * Modifying the Startup Sequence::  and turnkey applications.
14041: @end menu
14042: 
14043: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14044: @section Image Licensing Issues
14045: @cindex license for images
14046: @cindex image license
14047: 
14048: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14049: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14050: original image; i.e., according to copyright law it is a derived work of
14051: the original image.
14052: 
14053: Since Gforth is distributed under the GNU GPL, the newly created image
14054: falls under the GNU GPL, too. In particular, this means that if you
14055: distribute the image, you have to make all of the sources for the image
14056: available, including those you wrote.  For details see @ref{Copying, ,
14057: GNU General Public License (Section 3)}.
14058: 
14059: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14060: contains only code compiled from the sources you gave it; if none of
14061: these sources is under the GPL, the terms discussed above do not apply
14062: to the image. However, if your image needs an engine (a gforth binary)
14063: that is under the GPL, you should make sure that you distribute both in
14064: a way that is at most a @emph{mere aggregation}, if you don't want the
14065: terms of the GPL to apply to the image.
14066: 
14067: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
14068: @section Image File Background
14069: @cindex image file background
14070: 
14071: Gforth consists not only of primitives (in the engine), but also of
14072: definitions written in Forth. Since the Forth compiler itself belongs to
14073: those definitions, it is not possible to start the system with the
14074: engine and the Forth source alone. Therefore we provide the Forth
14075: code as an image file in nearly executable form. When Gforth starts up,
14076: a C routine loads the image file into memory, optionally relocates the
14077: addresses, then sets up the memory (stacks etc.) according to
14078: information in the image file, and (finally) starts executing Forth
14079: code.
14080: 
14081: The image file variants represent different compromises between the
14082: goals of making it easy to generate image files and making them
14083: portable.
14084: 
14085: @cindex relocation at run-time
14086: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
14087: run-time. This avoids many of the complications discussed below (image
14088: files are data relocatable without further ado), but costs performance
14089: (one addition per memory access).
14090: 
14091: @cindex relocation at load-time
14092: By contrast, the Gforth loader performs relocation at image load time. The
14093: loader also has to replace tokens that represent primitive calls with the
14094: appropriate code-field addresses (or code addresses in the case of
14095: direct threading).
14096: 
14097: There are three kinds of image files, with different degrees of
14098: relocatability: non-relocatable, data-relocatable, and fully relocatable
14099: image files.
14100: 
14101: @cindex image file loader
14102: @cindex relocating loader
14103: @cindex loader for image files
14104: These image file variants have several restrictions in common; they are
14105: caused by the design of the image file loader:
14106: 
14107: @itemize @bullet
14108: @item
14109: There is only one segment; in particular, this means, that an image file
14110: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
14111: them). The contents of the stacks are not represented, either.
14112: 
14113: @item
14114: The only kinds of relocation supported are: adding the same offset to
14115: all cells that represent data addresses; and replacing special tokens
14116: with code addresses or with pieces of machine code.
14117: 
14118: If any complex computations involving addresses are performed, the
14119: results cannot be represented in the image file. Several applications that
14120: use such computations come to mind:
14121: @itemize @minus
14122: @item
14123: Hashing addresses (or data structures which contain addresses) for table
14124: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14125: purpose, you will have no problem, because the hash tables are
14126: recomputed automatically when the system is started. If you use your own
14127: hash tables, you will have to do something similar.
14128: 
14129: @item
14130: There's a cute implementation of doubly-linked lists that uses
14131: @code{XOR}ed addresses. You could represent such lists as singly-linked
14132: in the image file, and restore the doubly-linked representation on
14133: startup.@footnote{In my opinion, though, you should think thrice before
14134: using a doubly-linked list (whatever implementation).}
14135: 
14136: @item
14137: The code addresses of run-time routines like @code{docol:} cannot be
14138: represented in the image file (because their tokens would be replaced by
14139: machine code in direct threaded implementations). As a workaround,
14140: compute these addresses at run-time with @code{>code-address} from the
14141: executions tokens of appropriate words (see the definitions of
14142: @code{docol:} and friends in @file{kernel/getdoers.fs}).
14143: 
14144: @item
14145: On many architectures addresses are represented in machine code in some
14146: shifted or mangled form. You cannot put @code{CODE} words that contain
14147: absolute addresses in this form in a relocatable image file. Workarounds
14148: are representing the address in some relative form (e.g., relative to
14149: the CFA, which is present in some register), or loading the address from
14150: a place where it is stored in a non-mangled form.
14151: @end itemize
14152: @end itemize
14153: 
14154: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14155: @section Non-Relocatable Image Files
14156: @cindex non-relocatable image files
14157: @cindex image file, non-relocatable
14158: 
14159: These files are simple memory dumps of the dictionary. They are specific
14160: to the executable (i.e., @file{gforth} file) they were created
14161: with. What's worse, they are specific to the place on which the
14162: dictionary resided when the image was created. Now, there is no
14163: guarantee that the dictionary will reside at the same place the next
14164: time you start Gforth, so there's no guarantee that a non-relocatable
14165: image will work the next time (Gforth will complain instead of crashing,
14166: though).
14167: 
14168: You can create a non-relocatable image file with
14169: 
14170: 
14171: doc-savesystem
14172: 
14173: 
14174: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14175: @section Data-Relocatable Image Files
14176: @cindex data-relocatable image files
14177: @cindex image file, data-relocatable
14178: 
14179: These files contain relocatable data addresses, but fixed code addresses
14180: (instead of tokens). They are specific to the executable (i.e.,
14181: @file{gforth} file) they were created with. For direct threading on some
14182: architectures (e.g., the i386), data-relocatable images do not work. You
14183: get a data-relocatable image, if you use @file{gforthmi} with a
14184: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14185: Relocatable Image Files}).
14186: 
14187: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14188: @section Fully Relocatable Image Files
14189: @cindex fully relocatable image files
14190: @cindex image file, fully relocatable
14191: 
14192: @cindex @file{kern*.fi}, relocatability
14193: @cindex @file{gforth.fi}, relocatability
14194: These image files have relocatable data addresses, and tokens for code
14195: addresses. They can be used with different binaries (e.g., with and
14196: without debugging) on the same machine, and even across machines with
14197: the same data formats (byte order, cell size, floating point
14198: format). However, they are usually specific to the version of Gforth
14199: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14200: are fully relocatable.
14201: 
14202: There are two ways to create a fully relocatable image file:
14203: 
14204: @menu
14205: * gforthmi::                    The normal way
14206: * cross.fs::                    The hard way
14207: @end menu
14208: 
14209: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14210: @subsection @file{gforthmi}
14211: @cindex @file{comp-i.fs}
14212: @cindex @file{gforthmi}
14213: 
14214: You will usually use @file{gforthmi}. If you want to create an
14215: image @i{file} that contains everything you would load by invoking
14216: Gforth with @code{gforth @i{options}}, you simply say:
14217: @example
14218: gforthmi @i{file} @i{options}
14219: @end example
14220: 
14221: E.g., if you want to create an image @file{asm.fi} that has the file
14222: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14223: like this:
14224: 
14225: @example
14226: gforthmi asm.fi asm.fs
14227: @end example
14228: 
14229: @file{gforthmi} is implemented as a sh script and works like this: It
14230: produces two non-relocatable images for different addresses and then
14231: compares them. Its output reflects this: first you see the output (if
14232: any) of the two Gforth invocations that produce the non-relocatable image
14233: files, then you see the output of the comparing program: It displays the
14234: offset used for data addresses and the offset used for code addresses;
14235: moreover, for each cell that cannot be represented correctly in the
14236: image files, it displays a line like this:
14237: 
14238: @example
14239:      78DC         BFFFFA50         BFFFFA40
14240: @end example
14241: 
14242: This means that at offset $78dc from @code{forthstart}, one input image
14243: contains $bffffa50, and the other contains $bffffa40. Since these cells
14244: cannot be represented correctly in the output image, you should examine
14245: these places in the dictionary and verify that these cells are dead
14246: (i.e., not read before they are written).
14247: 
14248: @cindex --application, @code{gforthmi} option
14249: If you insert the option @code{--application} in front of the image file
14250: name, you will get an image that uses the @code{--appl-image} option
14251: instead of the @code{--image-file} option (@pxref{Invoking
14252: Gforth}). When you execute such an image on Unix (by typing the image
14253: name as command), the Gforth engine will pass all options to the image
14254: instead of trying to interpret them as engine options.
14255: 
14256: If you type @file{gforthmi} with no arguments, it prints some usage
14257: instructions.
14258: 
14259: @cindex @code{savesystem} during @file{gforthmi}
14260: @cindex @code{bye} during @file{gforthmi}
14261: @cindex doubly indirect threaded code
14262: @cindex environment variables
14263: @cindex @code{GFORTHD} -- environment variable
14264: @cindex @code{GFORTH} -- environment variable
14265: @cindex @code{gforth-ditc}
14266: There are a few wrinkles: After processing the passed @i{options}, the
14267: words @code{savesystem} and @code{bye} must be visible. A special doubly
14268: indirect threaded version of the @file{gforth} executable is used for
14269: creating the non-relocatable images; you can pass the exact filename of
14270: this executable through the environment variable @code{GFORTHD}
14271: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14272: indirect threaded, you will not get a fully relocatable image, but a
14273: data-relocatable image (because there is no code address offset). The
14274: normal @file{gforth} executable is used for creating the relocatable
14275: image; you can pass the exact filename of this executable through the
14276: environment variable @code{GFORTH}.
14277: 
14278: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
14279: @subsection @file{cross.fs}
14280: @cindex @file{cross.fs}
14281: @cindex cross-compiler
14282: @cindex metacompiler
14283: @cindex target compiler
14284: 
14285: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14286: programming language (@pxref{Cross Compiler}).
14287: 
14288: @code{cross} allows you to create image files for machines with
14289: different data sizes and data formats than the one used for generating
14290: the image file. You can also use it to create an application image that
14291: does not contain a Forth compiler. These features are bought with
14292: restrictions and inconveniences in programming. E.g., addresses have to
14293: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14294: order to make the code relocatable.
14295: 
14296: 
14297: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14298: @section Stack and Dictionary Sizes
14299: @cindex image file, stack and dictionary sizes
14300: @cindex dictionary size default
14301: @cindex stack size default
14302: 
14303: If you invoke Gforth with a command line flag for the size
14304: (@pxref{Invoking Gforth}), the size you specify is stored in the
14305: dictionary. If you save the dictionary with @code{savesystem} or create
14306: an image with @file{gforthmi}, this size will become the default
14307: for the resulting image file. E.g., the following will create a
14308: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14309: 
14310: @example
14311: gforthmi gforth.fi -m 1M
14312: @end example
14313: 
14314: In other words, if you want to set the default size for the dictionary
14315: and the stacks of an image, just invoke @file{gforthmi} with the
14316: appropriate options when creating the image.
14317: 
14318: @cindex stack size, cache-friendly
14319: Note: For cache-friendly behaviour (i.e., good performance), you should
14320: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14321: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14322: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14323: 
14324: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14325: @section Running Image Files
14326: @cindex running image files
14327: @cindex invoking image files
14328: @cindex image file invocation
14329: 
14330: @cindex -i, invoke image file
14331: @cindex --image file, invoke image file
14332: You can invoke Gforth with an image file @i{image} instead of the
14333: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14334: @example
14335: gforth -i @i{image}
14336: @end example
14337: 
14338: @cindex executable image file
14339: @cindex image file, executable
14340: If your operating system supports starting scripts with a line of the
14341: form @code{#! ...}, you just have to type the image file name to start
14342: Gforth with this image file (note that the file extension @code{.fi} is
14343: just a convention). I.e., to run Gforth with the image file @i{image},
14344: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14345: This works because every @code{.fi} file starts with a line of this
14346: format:
14347: 
14348: @example
14349: #! /usr/local/bin/gforth-0.4.0 -i
14350: @end example
14351: 
14352: The file and pathname for the Gforth engine specified on this line is
14353: the specific Gforth executable that it was built against; i.e. the value
14354: of the environment variable @code{GFORTH} at the time that
14355: @file{gforthmi} was executed.
14356: 
14357: You can make use of the same shell capability to make a Forth source
14358: file into an executable. For example, if you place this text in a file:
14359: 
14360: @example
14361: #! /usr/local/bin/gforth
14362: 
14363: ." Hello, world" CR
14364: bye
14365: @end example
14366: 
14367: @noindent
14368: and then make the file executable (chmod +x in Unix), you can run it
14369: directly from the command line. The sequence @code{#!} is used in two
14370: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14371: system@footnote{The Unix kernel actually recognises two types of files:
14372: executable files and files of data, where the data is processed by an
14373: interpreter that is specified on the ``interpreter line'' -- the first
14374: line of the file, starting with the sequence #!. There may be a small
14375: limit (e.g., 32) on the number of characters that may be specified on
14376: the interpreter line.} secondly it is treated as a comment character by
14377: Gforth. Because of the second usage, a space is required between
14378: @code{#!} and the path to the executable (moreover, some Unixes
14379: require the sequence @code{#! /}).
14380: 
14381: The disadvantage of this latter technique, compared with using
14382: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14383: compiled on-the-fly, each time the program is invoked.
14384: 
14385: doc-#!
14386: 
14387: 
14388: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
14389: @section Modifying the Startup Sequence
14390: @cindex startup sequence for image file
14391: @cindex image file initialization sequence
14392: @cindex initialization sequence of image file
14393: 
14394: You can add your own initialization to the startup sequence of an image
14395: through the deferred word @code{'cold}. @code{'cold} is invoked just
14396: before the image-specific command line processing (i.e., loading files
14397: and evaluating (@code{-e}) strings) starts.
14398: 
14399: A sequence for adding your initialization usually looks like this:
14400: 
14401: @example
14402: :noname
14403:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14404:     ... \ your stuff
14405: ; IS 'cold
14406: @end example
14407: 
14408: @cindex turnkey image files
14409: @cindex image file, turnkey applications
14410: You can make a turnkey image by letting @code{'cold} execute a word
14411: (your turnkey application) that never returns; instead, it exits Gforth
14412: via @code{bye} or @code{throw}.
14413: 
14414: You can access the (image-specific) command-line arguments through
14415: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14416: arguments}).
14417: 
14418: If @code{'cold} exits normally, Gforth processes the command-line
14419: arguments as files to be loaded and strings to be evaluated.  Therefore,
14420: @code{'cold} should remove the arguments it has used in this case.
14421: 
14422: doc-'cold
14423: 
14424: @c ******************************************************************
14425: @node Engine, Cross Compiler, Image Files, Top
14426: @chapter Engine
14427: @cindex engine
14428: @cindex virtual machine
14429: 
14430: Reading this chapter is not necessary for programming with Gforth. It
14431: may be helpful for finding your way in the Gforth sources.
14432: 
14433: The ideas in this section have also been published in the following
14434: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14435: Forth-Tagung '93; M. Anton Ertl,
14436: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14437: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14438: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14439: Threaded code variations and optimizations (extended version)}},
14440: Forth-Tagung '02.
14441: 
14442: @menu
14443: * Portability::                 
14444: * Threading::                   
14445: * Primitives::                  
14446: * Performance::                 
14447: @end menu
14448: 
14449: @node Portability, Threading, Engine, Engine
14450: @section Portability
14451: @cindex engine portability
14452: 
14453: An important goal of the Gforth Project is availability across a wide
14454: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14455: achieved this goal by manually coding the engine in assembly language
14456: for several then-popular processors. This approach is very
14457: labor-intensive and the results are short-lived due to progress in
14458: computer architecture.
14459: 
14460: @cindex C, using C for the engine
14461: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14462: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14463: particularly popular for UNIX-based Forths due to the large variety of
14464: architectures of UNIX machines. Unfortunately an implementation in C
14465: does not mix well with the goals of efficiency and with using
14466: traditional techniques: Indirect or direct threading cannot be expressed
14467: in C, and switch threading, the fastest technique available in C, is
14468: significantly slower. Another problem with C is that it is very
14469: cumbersome to express double integer arithmetic.
14470: 
14471: @cindex GNU C for the engine
14472: @cindex long long
14473: Fortunately, there is a portable language that does not have these
14474: limitations: GNU C, the version of C processed by the GNU C compiler
14475: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14476: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14477: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14478: threading possible, its @code{long long} type (@pxref{Long Long, ,
14479: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14480: double numbers on many systems.  GNU C is freely available on all
14481: important (and many unimportant) UNIX machines, VMS, 80386s running
14482: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14483: on all these machines.
14484: 
14485: Writing in a portable language has the reputation of producing code that
14486: is slower than assembly. For our Forth engine we repeatedly looked at
14487: the code produced by the compiler and eliminated most compiler-induced
14488: inefficiencies by appropriate changes in the source code.
14489: 
14490: @cindex explicit register declarations
14491: @cindex --enable-force-reg, configuration flag
14492: @cindex -DFORCE_REG
14493: However, register allocation cannot be portably influenced by the
14494: programmer, leading to some inefficiencies on register-starved
14495: machines. We use explicit register declarations (@pxref{Explicit Reg
14496: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14497: improve the speed on some machines. They are turned on by using the
14498: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14499: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14500: machine, but also on the compiler version: On some machines some
14501: compiler versions produce incorrect code when certain explicit register
14502: declarations are used. So by default @code{-DFORCE_REG} is not used.
14503: 
14504: @node Threading, Primitives, Portability, Engine
14505: @section Threading
14506: @cindex inner interpreter implementation
14507: @cindex threaded code implementation
14508: 
14509: @cindex labels as values
14510: GNU C's labels as values extension (available since @code{gcc-2.0},
14511: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14512: makes it possible to take the address of @i{label} by writing
14513: @code{&&@i{label}}.  This address can then be used in a statement like
14514: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14515: @code{goto x}.
14516: 
14517: @cindex @code{NEXT}, indirect threaded
14518: @cindex indirect threaded inner interpreter
14519: @cindex inner interpreter, indirect threaded
14520: With this feature an indirect threaded @code{NEXT} looks like:
14521: @example
14522: cfa = *ip++;
14523: ca = *cfa;
14524: goto *ca;
14525: @end example
14526: @cindex instruction pointer
14527: For those unfamiliar with the names: @code{ip} is the Forth instruction
14528: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14529: execution token and points to the code field of the next word to be
14530: executed; The @code{ca} (code address) fetched from there points to some
14531: executable code, e.g., a primitive or the colon definition handler
14532: @code{docol}.
14533: 
14534: @cindex @code{NEXT}, direct threaded
14535: @cindex direct threaded inner interpreter
14536: @cindex inner interpreter, direct threaded
14537: Direct threading is even simpler:
14538: @example
14539: ca = *ip++;
14540: goto *ca;
14541: @end example
14542: 
14543: Of course we have packaged the whole thing neatly in macros called
14544: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14545: 
14546: @menu
14547: * Scheduling::                  
14548: * Direct or Indirect Threaded?::  
14549: * Dynamic Superinstructions::   
14550: * DOES>::                       
14551: @end menu
14552: 
14553: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14554: @subsection Scheduling
14555: @cindex inner interpreter optimization
14556: 
14557: There is a little complication: Pipelined and superscalar processors,
14558: i.e., RISC and some modern CISC machines can process independent
14559: instructions while waiting for the results of an instruction. The
14560: compiler usually reorders (schedules) the instructions in a way that
14561: achieves good usage of these delay slots. However, on our first tries
14562: the compiler did not do well on scheduling primitives. E.g., for
14563: @code{+} implemented as
14564: @example
14565: n=sp[0]+sp[1];
14566: sp++;
14567: sp[0]=n;
14568: NEXT;
14569: @end example
14570: the @code{NEXT} comes strictly after the other code, i.e., there is
14571: nearly no scheduling. After a little thought the problem becomes clear:
14572: The compiler cannot know that @code{sp} and @code{ip} point to different
14573: addresses (and the version of @code{gcc} we used would not know it even
14574: if it was possible), so it could not move the load of the cfa above the
14575: store to the TOS. Indeed the pointers could be the same, if code on or
14576: very near the top of stack were executed. In the interest of speed we
14577: chose to forbid this probably unused ``feature'' and helped the compiler
14578: in scheduling: @code{NEXT} is divided into several parts:
14579: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14580: like:
14581: @example
14582: NEXT_P0;
14583: n=sp[0]+sp[1];
14584: sp++;
14585: NEXT_P1;
14586: sp[0]=n;
14587: NEXT_P2;
14588: @end example
14589: 
14590: There are various schemes that distribute the different operations of
14591: NEXT between these parts in several ways; in general, different schemes
14592: perform best on different processors.  We use a scheme for most
14593: architectures that performs well for most processors of this
14594: architecture; in the future we may switch to benchmarking and chosing
14595: the scheme on installation time.
14596: 
14597: 
14598: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
14599: @subsection Direct or Indirect Threaded?
14600: @cindex threading, direct or indirect?
14601: 
14602: Threaded forth code consists of references to primitives (simple machine
14603: code routines like @code{+}) and to non-primitives (e.g., colon
14604: definitions, variables, constants); for a specific class of
14605: non-primitives (e.g., variables) there is one code routine (e.g.,
14606: @code{dovar}), but each variable needs a separate reference to its data.
14607: 
14608: Traditionally Forth has been implemented as indirect threaded code,
14609: because this allows to use only one cell to reference a non-primitive
14610: (basically you point to the data, and find the code address there).
14611: 
14612: @cindex primitive-centric threaded code
14613: However, threaded code in Gforth (since 0.6.0) uses two cells for
14614: non-primitives, one for the code address, and one for the data address;
14615: the data pointer is an immediate argument for the virtual machine
14616: instruction represented by the code address.  We call this
14617: @emph{primitive-centric} threaded code, because all code addresses point
14618: to simple primitives.  E.g., for a variable, the code address is for
14619: @code{lit} (also used for integer literals like @code{99}).
14620: 
14621: Primitive-centric threaded code allows us to use (faster) direct
14622: threading as dispatch method, completely portably (direct threaded code
14623: in Gforth before 0.6.0 required architecture-specific code).  It also
14624: eliminates the performance problems related to I-cache consistency that
14625: 386 implementations have with direct threaded code, and allows
14626: additional optimizations.
14627: 
14628: @cindex hybrid direct/indirect threaded code
14629: There is a catch, however: the @var{xt} parameter of @code{execute} can
14630: occupy only one cell, so how do we pass non-primitives with their code
14631: @emph{and} data addresses to them?  Our answer is to use indirect
14632: threaded dispatch for @code{execute} and other words that use a
14633: single-cell xt.  So, normal threaded code in colon definitions uses
14634: direct threading, and @code{execute} and similar words, which dispatch
14635: to xts on the data stack, use indirect threaded code.  We call this
14636: @emph{hybrid direct/indirect} threaded code.
14637: 
14638: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14639: @cindex gforth engine
14640: @cindex gforth-fast engine
14641: The engines @command{gforth} and @command{gforth-fast} use hybrid
14642: direct/indirect threaded code.  This means that with these engines you
14643: cannot use @code{,} to compile an xt.  Instead, you have to use
14644: @code{compile,}.
14645: 
14646: @cindex gforth-itc engine
14647: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14648: This engine uses plain old indirect threaded code.  It still compiles in
14649: a primitive-centric style, so you cannot use @code{compile,} instead of
14650: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
14651: ... [}).  If you want to do that, you have to use @command{gforth-itc}
14652: and execute @code{' , is compile,}.  Your program can check if it is
14653: running on a hybrid direct/indirect threaded engine or a pure indirect
14654: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14655: 
14656: 
14657: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14658: @subsection Dynamic Superinstructions
14659: @cindex Dynamic superinstructions with replication
14660: @cindex Superinstructions
14661: @cindex Replication
14662: 
14663: The engines @command{gforth} and @command{gforth-fast} use another
14664: optimization: Dynamic superinstructions with replication.  As an
14665: example, consider the following colon definition:
14666: 
14667: @example
14668: : squared ( n1 -- n2 )
14669:   dup * ;
14670: @end example
14671: 
14672: Gforth compiles this into the threaded code sequence
14673: 
14674: @example
14675: dup
14676: *
14677: ;s
14678: @end example
14679: 
14680: In normal direct threaded code there is a code address occupying one
14681: cell for each of these primitives.  Each code address points to a
14682: machine code routine, and the interpreter jumps to this machine code in
14683: order to execute the primitive.  The routines for these three
14684: primitives are (in @command{gforth-fast} on the 386):
14685: 
14686: @example
14687: Code dup  
14688: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
14689: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
14690: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
14691: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14692: end-code
14693: Code *  
14694: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
14695: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
14696: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
14697: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
14698: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14699: end-code
14700: Code ;s  
14701: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
14702: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
14703: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
14704: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14705: end-code
14706: @end example
14707: 
14708: With dynamic superinstructions and replication the compiler does not
14709: just lay down the threaded code, but also copies the machine code
14710: fragments, usually without the jump at the end.
14711: 
14712: @example
14713: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
14714: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
14715: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
14716: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
14717: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
14718: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
14719: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
14720: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
14721: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
14722: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
14723: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
14724: @end example
14725: 
14726: Only when a threaded-code control-flow change happens (e.g., in
14727: @code{;s}), the jump is appended.  This optimization eliminates many of
14728: these jumps and makes the rest much more predictable.  The speedup
14729: depends on the processor and the application; on the Athlon and Pentium
14730: III this optimization typically produces a speedup by a factor of 2.
14731: 
14732: The code addresses in the direct-threaded code are set to point to the
14733: appropriate points in the copied machine code, in this example like
14734: this:
14735: 
14736: @example
14737: primitive  code address
14738:    dup       $4057D27D
14739:    *         $4057D286
14740:    ;s        $4057D292
14741: @end example
14742: 
14743: Thus there can be threaded-code jumps to any place in this piece of
14744: code.  This also simplifies decompilation quite a bit.
14745: 
14746: @cindex --no-dynamic command-line option
14747: @cindex --no-super command-line option
14748: You can disable this optimization with @option{--no-dynamic}.  You can
14749: use the copying without eliminating the jumps (i.e., dynamic
14750: replication, but without superinstructions) with @option{--no-super};
14751: this gives the branch prediction benefit alone; the effect on
14752: performance depends on the CPU; on the Athlon and Pentium III the
14753: speedup is a little less than for dynamic superinstructions with
14754: replication.
14755: 
14756: @cindex patching threaded code
14757: One use of these options is if you want to patch the threaded code.
14758: With superinstructions, many of the dispatch jumps are eliminated, so
14759: patching often has no effect.  These options preserve all the dispatch
14760: jumps.
14761: 
14762: @cindex --dynamic command-line option
14763: On some machines dynamic superinstructions are disabled by default,
14764: because it is unsafe on these machines.  However, if you feel
14765: adventurous, you can enable it with @option{--dynamic}.
14766: 
14767: @node DOES>,  , Dynamic Superinstructions, Threading
14768: @subsection DOES>
14769: @cindex @code{DOES>} implementation
14770: 
14771: @cindex @code{dodoes} routine
14772: @cindex @code{DOES>}-code
14773: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14774: the chunk of code executed by every word defined by a
14775: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14776: this is only needed if the xt of the word is @code{execute}d. The main
14777: problem here is: How to find the Forth code to be executed, i.e. the
14778: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14779: solutions:
14780: 
14781: In fig-Forth the code field points directly to the @code{dodoes} and the
14782: @code{DOES>}-code address is stored in the cell after the code address
14783: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14784: illegal in the Forth-79 and all later standards, because in fig-Forth
14785: this address lies in the body (which is illegal in these
14786: standards). However, by making the code field larger for all words this
14787: solution becomes legal again.  We use this approach.  Leaving a cell
14788: unused in most words is a bit wasteful, but on the machines we are
14789: targeting this is hardly a problem.
14790: 
14791: 
14792: @node Primitives, Performance, Threading, Engine
14793: @section Primitives
14794: @cindex primitives, implementation
14795: @cindex virtual machine instructions, implementation
14796: 
14797: @menu
14798: * Automatic Generation::        
14799: * TOS Optimization::            
14800: * Produced code::               
14801: @end menu
14802: 
14803: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14804: @subsection Automatic Generation
14805: @cindex primitives, automatic generation
14806: 
14807: @cindex @file{prims2x.fs}
14808: 
14809: Since the primitives are implemented in a portable language, there is no
14810: longer any need to minimize the number of primitives. On the contrary,
14811: having many primitives has an advantage: speed. In order to reduce the
14812: number of errors in primitives and to make programming them easier, we
14813: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14814: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14815: generates most (and sometimes all) of the C code for a primitive from
14816: the stack effect notation.  The source for a primitive has the following
14817: form:
14818: 
14819: @cindex primitive source format
14820: @format
14821: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
14822: [@code{""}@i{glossary entry}@code{""}]
14823: @i{C code}
14824: [@code{:}
14825: @i{Forth code}]
14826: @end format
14827: 
14828: The items in brackets are optional. The category and glossary fields
14829: are there for generating the documentation, the Forth code is there
14830: for manual implementations on machines without GNU C. E.g., the source
14831: for the primitive @code{+} is:
14832: @example
14833: +    ( n1 n2 -- n )   core    plus
14834: n = n1+n2;
14835: @end example
14836: 
14837: This looks like a specification, but in fact @code{n = n1+n2} is C
14838: code. Our primitive generation tool extracts a lot of information from
14839: the stack effect notations@footnote{We use a one-stack notation, even
14840: though we have separate data and floating-point stacks; The separate
14841: notation can be generated easily from the unified notation.}: The number
14842: of items popped from and pushed on the stack, their type, and by what
14843: name they are referred to in the C code. It then generates a C code
14844: prelude and postlude for each primitive. The final C code for @code{+}
14845: looks like this:
14846: 
14847: @example
14848: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
14849: /*  */                          /* documentation */
14850: NAME("+")                       /* debugging output (with -DDEBUG) */
14851: @{
14852: DEF_CA                          /* definition of variable ca (indirect threading) */
14853: Cell n1;                        /* definitions of variables */
14854: Cell n2;
14855: Cell n;
14856: NEXT_P0;                        /* NEXT part 0 */
14857: n1 = (Cell) sp[1];              /* input */
14858: n2 = (Cell) TOS;
14859: sp += 1;                        /* stack adjustment */
14860: @{
14861: n = n1+n2;                      /* C code taken from the source */
14862: @}
14863: NEXT_P1;                        /* NEXT part 1 */
14864: TOS = (Cell)n;                  /* output */
14865: NEXT_P2;                        /* NEXT part 2 */
14866: @}
14867: @end example
14868: 
14869: This looks long and inefficient, but the GNU C compiler optimizes quite
14870: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14871: HP RISC machines: Defining the @code{n}s does not produce any code, and
14872: using them as intermediate storage also adds no cost.
14873: 
14874: There are also other optimizations that are not illustrated by this
14875: example: assignments between simple variables are usually for free (copy
14876: propagation). If one of the stack items is not used by the primitive
14877: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
14878: (dead code elimination). On the other hand, there are some things that
14879: the compiler does not do, therefore they are performed by
14880: @file{prims2x.fs}: The compiler does not optimize code away that stores
14881: a stack item to the place where it just came from (e.g., @code{over}).
14882: 
14883: While programming a primitive is usually easy, there are a few cases
14884: where the programmer has to take the actions of the generator into
14885: account, most notably @code{?dup}, but also words that do not (always)
14886: fall through to @code{NEXT}.
14887: 
14888: For more information
14889: 
14890: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14891: @subsection TOS Optimization
14892: @cindex TOS optimization for primitives
14893: @cindex primitives, keeping the TOS in a register
14894: 
14895: An important optimization for stack machine emulators, e.g., Forth
14896: engines, is keeping  one or more of the top stack items in
14897: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
14898: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
14899: @itemize @bullet
14900: @item
14901: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
14902: due to fewer loads from and stores to the stack.
14903: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14904: @i{y<n}, due to additional moves between registers.
14905: @end itemize
14906: 
14907: @cindex -DUSE_TOS
14908: @cindex -DUSE_NO_TOS
14909: In particular, keeping one item in a register is never a disadvantage,
14910: if there are enough registers. Keeping two items in registers is a
14911: disadvantage for frequent words like @code{?branch}, constants,
14912: variables, literals and @code{i}. Therefore our generator only produces
14913: code that keeps zero or one items in registers. The generated C code
14914: covers both cases; the selection between these alternatives is made at
14915: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14916: code for @code{+} is just a simple variable name in the one-item case,
14917: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14918: GNU C compiler tries to keep simple variables like @code{TOS} in
14919: registers, and it usually succeeds, if there are enough registers.
14920: 
14921: @cindex -DUSE_FTOS
14922: @cindex -DUSE_NO_FTOS
14923: The primitive generator performs the TOS optimization for the
14924: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14925: operations the benefit of this optimization is even larger:
14926: floating-point operations take quite long on most processors, but can be
14927: performed in parallel with other operations as long as their results are
14928: not used. If the FP-TOS is kept in a register, this works. If
14929: it is kept on the stack, i.e., in memory, the store into memory has to
14930: wait for the result of the floating-point operation, lengthening the
14931: execution time of the primitive considerably.
14932: 
14933: The TOS optimization makes the automatic generation of primitives a
14934: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14935: @code{TOS} is not sufficient. There are some special cases to
14936: consider:
14937: @itemize @bullet
14938: @item In the case of @code{dup ( w -- w w )} the generator must not
14939: eliminate the store to the original location of the item on the stack,
14940: if the TOS optimization is turned on.
14941: @item Primitives with stack effects of the form @code{--}
14942: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14943: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
14944: must load the TOS from the stack at the end. But for the null stack
14945: effect @code{--} no stores or loads should be generated.
14946: @end itemize
14947: 
14948: @node Produced code,  , TOS Optimization, Primitives
14949: @subsection Produced code
14950: @cindex primitives, assembly code listing
14951: 
14952: @cindex @file{engine.s}
14953: To see what assembly code is produced for the primitives on your machine
14954: with your compiler and your flag settings, type @code{make engine.s} and
14955: look at the resulting file @file{engine.s}.  Alternatively, you can also
14956: disassemble the code of primitives with @code{see} on some architectures.
14957: 
14958: @node  Performance,  , Primitives, Engine
14959: @section Performance
14960: @cindex performance of some Forth interpreters
14961: @cindex engine performance
14962: @cindex benchmarking Forth systems
14963: @cindex Gforth performance
14964: 
14965: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
14966: impossible to write a significantly faster threaded-code engine.
14967: 
14968: On register-starved machines like the 386 architecture processors
14969: improvements are possible, because @code{gcc} does not utilize the
14970: registers as well as a human, even with explicit register declarations;
14971: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14972: and hand-tuned it for the 486; this system is 1.19 times faster on the
14973: Sieve benchmark on a 486DX2/66 than Gforth compiled with
14974: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
14975: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14976: registers fit in real registers (and we can even afford to use the TOS
14977: optimization), resulting in a speedup of 1.14 on the sieve over the
14978: earlier results.  And dynamic superinstructions provide another speedup
14979: (but only around a factor 1.2 on the 486).
14980: 
14981: @cindex Win32Forth performance
14982: @cindex NT Forth performance
14983: @cindex eforth performance
14984: @cindex ThisForth performance
14985: @cindex PFE performance
14986: @cindex TILE performance
14987: The potential advantage of assembly language implementations is not
14988: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
14989: (direct threaded, compiled with @code{gcc-2.95.1} and
14990: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14991: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14992: (with and without peephole (aka pinhole) optimization of the threaded
14993: code); all these systems were written in assembly language. We also
14994: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14995: with @code{gcc-2.6.3} with the default configuration for Linux:
14996: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14997: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14998: employs peephole optimization of the threaded code) and TILE (compiled
14999: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15000: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15001: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15002: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15003: then extended it to run the benchmarks, added the peephole optimizer,
15004: ran the benchmarks and reported the results.
15005: 
15006: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15007: matrix multiplication come from the Stanford integer benchmarks and have
15008: been translated into Forth by Martin Fraeman; we used the versions
15009: included in the TILE Forth package, but with bigger data set sizes; and
15010: a recursive Fibonacci number computation for benchmarking calling
15011: performance. The following table shows the time taken for the benchmarks
15012: scaled by the time taken by Gforth (in other words, it shows the speedup
15013: factor that Gforth achieved over the other systems).
15014: 
15015: @example
15016: relative       Win32-    NT       eforth       This-      
15017: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
15018: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
15019: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
15020: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
15021: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
15022: @end example
15023: 
15024: You may be quite surprised by the good performance of Gforth when
15025: compared with systems written in assembly language. One important reason
15026: for the disappointing performance of these other systems is probably
15027: that they are not written optimally for the 486 (e.g., they use the
15028: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15029: but costly method for relocating the Forth image: like @code{cforth}, it
15030: computes the actual addresses at run time, resulting in two address
15031: computations per @code{NEXT} (@pxref{Image File Background}).
15032: 
15033: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15034: explained with the self-imposed restriction of the latter systems to
15035: standard C, which makes efficient threading impossible (however, the
15036: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
15037: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15038: Moreover, current C compilers have a hard time optimizing other aspects
15039: of the ThisForth and the TILE source.
15040: 
15041: The performance of Gforth on 386 architecture processors varies widely
15042: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15043: allocate any of the virtual machine registers into real machine
15044: registers by itself and would not work correctly with explicit register
15045: declarations, giving a significantly slower engine (on a 486DX2/66
15046: running the Sieve) than the one measured above.
15047: 
15048: Note that there have been several releases of Win32Forth since the
15049: release presented here, so the results presented above may have little
15050: predictive value for the performance of Win32Forth today (results for
15051: the current release on an i486DX2/66 are welcome).
15052: 
15053: @cindex @file{Benchres}
15054: In
15055: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15056: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
15057: Maierhofer (presented at EuroForth '95), an indirect threaded version of
15058: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15059: several native code systems; that version of Gforth is slower on a 486
15060: than the version used here. You can find a newer version of these
15061: measurements at
15062: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
15063: find numbers for Gforth on various machines in @file{Benchres}.
15064: 
15065: @c ******************************************************************
15066: @c @node Binding to System Library, Cross Compiler, Engine, Top
15067: @c @chapter Binding to System Library
15068: 
15069: @c ****************************************************************
15070: @node Cross Compiler, Bugs, Engine, Top
15071: @chapter Cross Compiler
15072: @cindex @file{cross.fs}
15073: @cindex cross-compiler
15074: @cindex metacompiler
15075: @cindex target compiler
15076: 
15077: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15078: mostly written in Forth, including crucial parts like the outer
15079: interpreter and compiler, it needs compiled Forth code to get
15080: started. The cross compiler allows to create new images for other
15081: architectures, even running under another Forth system.
15082: 
15083: @menu
15084: * Using the Cross Compiler::    
15085: * How the Cross Compiler Works::  
15086: @end menu
15087: 
15088: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
15089: @section Using the Cross Compiler
15090: 
15091: The cross compiler uses a language that resembles Forth, but isn't. The
15092: main difference is that you can execute Forth code after definition,
15093: while you usually can't execute the code compiled by cross, because the
15094: code you are compiling is typically for a different computer than the
15095: one you are compiling on.
15096: 
15097: @c anton: This chapter is somewhat different from waht I would expect: I
15098: @c would expect an explanation of the cross language and how to create an
15099: @c application image with it.  The section explains some aspects of
15100: @c creating a Gforth kernel.
15101: 
15102: The Makefile is already set up to allow you to create kernels for new
15103: architectures with a simple make command. The generic kernels using the
15104: GCC compiled virtual machine are created in the normal build process
15105: with @code{make}. To create a embedded Gforth executable for e.g. the
15106: 8086 processor (running on a DOS machine), type
15107: 
15108: @example
15109: make kernl-8086.fi
15110: @end example
15111: 
15112: This will use the machine description from the @file{arch/8086}
15113: directory to create a new kernel. A machine file may look like that:
15114: 
15115: @example
15116: \ Parameter for target systems                         06oct92py
15117: 
15118:     4 Constant cell             \ cell size in bytes
15119:     2 Constant cell<<           \ cell shift to bytes
15120:     5 Constant cell>bit         \ cell shift to bits
15121:     8 Constant bits/char        \ bits per character
15122:     8 Constant bits/byte        \ bits per byte [default: 8]
15123:     8 Constant float            \ bytes per float
15124:     8 Constant /maxalign        \ maximum alignment in bytes
15125: false Constant bigendian        \ byte order
15126: ( true=big, false=little )
15127: 
15128: include machpc.fs               \ feature list
15129: @end example
15130: 
15131: This part is obligatory for the cross compiler itself, the feature list
15132: is used by the kernel to conditionally compile some features in and out,
15133: depending on whether the target supports these features.
15134: 
15135: There are some optional features, if you define your own primitives,
15136: have an assembler, or need special, nonstandard preparation to make the
15137: boot process work. @code{asm-include} includes an assembler,
15138: @code{prims-include} includes primitives, and @code{>boot} prepares for
15139: booting.
15140: 
15141: @example
15142: : asm-include    ." Include assembler" cr
15143:   s" arch/8086/asm.fs" included ;
15144: 
15145: : prims-include  ." Include primitives" cr
15146:   s" arch/8086/prim.fs" included ;
15147: 
15148: : >boot          ." Prepare booting" cr
15149:   s" ' boot >body into-forth 1+ !" evaluate ;
15150: @end example
15151: 
15152: These words are used as sort of macro during the cross compilation in
15153: the file @file{kernel/main.fs}. Instead of using these macros, it would
15154: be possible --- but more complicated --- to write a new kernel project
15155: file, too.
15156: 
15157: @file{kernel/main.fs} expects the machine description file name on the
15158: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15159: @code{mach-file} leaves a counted string on the stack, or
15160: @code{machine-file} leaves an address, count pair of the filename on the
15161: stack.
15162: 
15163: The feature list is typically controlled using @code{SetValue}, generic
15164: files that are used by several projects can use @code{DefaultValue}
15165: instead. Both functions work like @code{Value}, when the value isn't
15166: defined, but @code{SetValue} works like @code{to} if the value is
15167: defined, and @code{DefaultValue} doesn't set anything, if the value is
15168: defined.
15169: 
15170: @example
15171: \ generic mach file for pc gforth                       03sep97jaw
15172: 
15173: true DefaultValue NIL  \ relocating
15174: 
15175: >ENVIRON
15176: 
15177: true DefaultValue file          \ controls the presence of the
15178:                                 \ file access wordset
15179: true DefaultValue OS            \ flag to indicate a operating system
15180: 
15181: true DefaultValue prims         \ true: primitives are c-code
15182: 
15183: true DefaultValue floating      \ floating point wordset is present
15184: 
15185: true DefaultValue glocals       \ gforth locals are present
15186:                                 \ will be loaded
15187: true DefaultValue dcomps        \ double number comparisons
15188: 
15189: true DefaultValue hash          \ hashing primitives are loaded/present
15190: 
15191: true DefaultValue xconds        \ used together with glocals,
15192:                                 \ special conditionals supporting gforths'
15193:                                 \ local variables
15194: true DefaultValue header        \ save a header information
15195: 
15196: true DefaultValue backtrace     \ enables backtrace code
15197: 
15198: false DefaultValue ec
15199: false DefaultValue crlf
15200: 
15201: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15202: 
15203: &16 KB          DefaultValue stack-size
15204: &15 KB &512 +   DefaultValue fstack-size
15205: &15 KB          DefaultValue rstack-size
15206: &14 KB &512 +   DefaultValue lstack-size
15207: @end example
15208: 
15209: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
15210: @section How the Cross Compiler Works
15211: 
15212: @node Bugs, Origin, Cross Compiler, Top
15213: @appendix Bugs
15214: @cindex bug reporting
15215: 
15216: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
15217: 
15218: If you find a bug, please submit a bug report through
15219: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
15220: 
15221: @itemize @bullet
15222: @item
15223: A program (or a sequence of keyboard commands) that reproduces the bug.
15224: @item
15225: A description of what you think constitutes the buggy behaviour.
15226: @item
15227: The Gforth version used (it is announced at the start of an
15228: interactive Gforth session).
15229: @item
15230: The machine and operating system (on Unix
15231: systems @code{uname -a} will report this information).
15232: @item
15233: The installation options (you can find the configure options at the
15234: start of @file{config.status}) and configuration (@code{configure}
15235: output or @file{config.cache}).
15236: @item
15237: A complete list of changes (if any) you (or your installer) have made to the
15238: Gforth sources.
15239: @end itemize
15240: 
15241: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15242: to Report Bugs, gcc.info, GNU C Manual}.
15243: 
15244: 
15245: @node Origin, Forth-related information, Bugs, Top
15246: @appendix Authors and Ancestors of Gforth
15247: 
15248: @section Authors and Contributors
15249: @cindex authors of Gforth
15250: @cindex contributors to Gforth
15251: 
15252: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
15253: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
15254: lot to the manual.  Assemblers and disassemblers were contributed by
15255: Andrew McKewan, Christian Pirker, and Bernd Thallner.  Lennart Benschop
15256: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15257: inspired us with their continuous feedback. Lennart Benshop contributed
15258: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15259: support for calling C libraries. Helpful comments also came from Paul
15260: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
15261: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15262: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15263: Gforth-0.2.1 there were also helpful comments from many others; thank
15264: you all, sorry for not listing you here (but digging through my mailbox
15265: to extract your names is on my to-do list).
15266: 
15267: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15268: and autoconf, among others), and to the creators of the Internet: Gforth
15269: was developed across the Internet, and its authors did not meet
15270: physically for the first 4 years of development.
15271: 
15272: @section Pedigree
15273: @cindex pedigree of Gforth
15274: 
15275: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
15276: significant part of the design of Gforth was prescribed by ANS Forth.
15277: 
15278: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
15279: 32 bit native code version of VolksForth for the Atari ST, written
15280: mostly by Dietrich Weineck.
15281: 
15282: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15283: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15284: the mid-80s and ported to the Atari ST in 1986.  It descends from F83.
15285: 
15286: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15287: Forth-83 standard. !! Pedigree? When?
15288: 
15289: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15290: 1979. Robert Selzer and Bill Ragsdale developed the original
15291: implementation of fig-Forth for the 6502 based on microForth.
15292: 
15293: The principal architect of microForth was Dean Sanderson. microForth was
15294: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15295: the 1802, and subsequently implemented on the 8080, the 6800 and the
15296: Z80.
15297: 
15298: All earlier Forth systems were custom-made, usually by Charles Moore,
15299: who discovered (as he puts it) Forth during the late 60s. The first full
15300: Forth existed in 1971.
15301: 
15302: A part of the information in this section comes from
15303: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15304: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15305: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15306: SIGPLAN Notices 28(3), 1993.  You can find more historical and
15307: genealogical information about Forth there.
15308: 
15309: @c ------------------------------------------------------------------
15310: @node Forth-related information, Licenses, Origin, Top
15311: @appendix Other Forth-related information
15312: @cindex Forth-related information
15313: 
15314: @c anton: I threw most of this stuff out, because it can be found through
15315: @c the FAQ and the FAQ is more likely to be up-to-date.
15316: 
15317: @cindex comp.lang.forth
15318: @cindex frequently asked questions
15319: There is an active news group (comp.lang.forth) discussing Forth
15320: (including Gforth) and Forth-related issues. Its
15321: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15322: (frequently asked questions and their answers) contains a lot of
15323: information on Forth.  You should read it before posting to
15324: comp.lang.forth.
15325: 
15326: The ANS Forth standard is most usable in its
15327: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
15328: 
15329: @c ---------------------------------------------------
15330: @node  Licenses, Word Index, Forth-related information, Top
15331: @appendix Licenses
15332: 
15333: @menu
15334: * GNU Free Documentation License::  License for copying this manual.
15335: * Copying::                         GPL (for copying this software).
15336: @end menu
15337: 
15338: @include fdl.texi
15339: 
15340: @include gpl.texi
15341: 
15342: 
15343: 
15344: @c ------------------------------------------------------------------
15345: @node Word Index, Concept Index, Licenses, Top
15346: @unnumbered Word Index
15347: 
15348: This index is a list of Forth words that have ``glossary'' entries
15349: within this manual. Each word is listed with its stack effect and
15350: wordset.
15351: 
15352: @printindex fn
15353: 
15354: @c anton: the name index seems superfluous given the word and concept indices.
15355: 
15356: @c @node Name Index, Concept Index, Word Index, Top
15357: @c @unnumbered Name Index
15358: 
15359: @c This index is a list of Forth words that have ``glossary'' entries
15360: @c within this manual.
15361: 
15362: @c @printindex ky
15363: 
15364: @c -------------------------------------------------------
15365: @node Concept Index,  , Word Index, Top
15366: @unnumbered Concept and Word Index
15367: 
15368: Not all entries listed in this index are present verbatim in the
15369: text. This index also duplicates, in abbreviated form, all of the words
15370: listed in the Word Index (only the names are listed for the words here).
15371: 
15372: @printindex cp
15373: 
15374: @bye
15375: 
15376: 
15377: 

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