File:  [gforth] / gforth / doc / gforth.ds
Revision 1.119: download - view: text, annotated - select for diffs
Mon Aug 25 14:17:49 2003 UTC (18 years, 2 months ago) by anton
Branches: MAIN
CVS tags: v0-6-2, HEAD
documentation updates
fixed some portability bugs in vmgen-ex and vmgen-ex2
updated copyright years

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: 
    4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    5: @comment 1. x-ref all ambiguous or implementation-defined features?
    6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
    7: @comment 3. words in miscellaneous section need a home.
    8: @comment 4. search for TODO for other minor and major works required.
    9: @comment 5. [rats] change all @var to @i in Forth source so that info
   10: @comment    file looks decent.
   11: @c          Not an improvement IMO - anton
   12: @c          and anyway, this should be taken up
   13: @c          with Karl Berry (the texinfo guy) - anton
   14: @c
   15: @c Karl Berry writes:
   16: @c  If they don't like the all-caps for @var Info output, all I can say is
   17: @c  that it's always been that way, and the usage of all-caps for
   18: @c  metavariables has a long tradition.  I think it's best to just let it be
   19: @c  what it is, for the sake of consistency among manuals.
   20: @c
   21: @comment .. would be useful to have a word that identified all deferred words
   22: @comment should semantics stuff in intro be moved to another section
   23: 
   24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
   25: 
   26: @comment %**start of header (This is for running Texinfo on a region.)
   27: @setfilename gforth.info
   28: @include version.texi
   29: @settitle Gforth Manual
   30: @c @syncodeindex pg cp
   31: 
   32: @macro progstyle {}
   33: Programming style note:
   34: @end macro
   35: 
   36: @macro assignment {}
   37: @table @i
   38: @item Assignment:
   39: @end macro
   40: @macro endassignment {}
   41: @end table
   42: @end macro
   43: 
   44: @comment macros for beautifying glossary entries
   45: @macro GLOSS-START {}
   46: @iftex
   47: @ninerm
   48: @end iftex
   49: @end macro
   50: 
   51: @macro GLOSS-END {}
   52: @iftex
   53: @rm
   54: @end iftex
   55: @end macro
   56: 
   57: @comment %**end of header (This is for running Texinfo on a region.)
   58: @copying
   59: This manual is for Gforth
   60: (version @value{VERSION}, @value{UPDATED}),
   61: a fast and portable implementation of the ANS Forth language
   62: 
   63: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
   64: 
   65: @quotation
   66: Permission is granted to copy, distribute and/or modify this document
   67: under the terms of the GNU Free Documentation License, Version 1.1 or
   68: any later version published by the Free Software Foundation; with no
   69: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
   70: and with the Back-Cover Texts as in (a) below.  A copy of the
   71: license is included in the section entitled ``GNU Free Documentation
   72: License.''
   73: 
   74: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
   75: this GNU Manual, like GNU software.  Copies published by the Free
   76: Software Foundation raise funds for GNU development.''
   77: @end quotation
   78: @end copying
   79: 
   80: @dircategory Software development
   81: @direntry
   82: * Gforth: (gforth).             A fast interpreter for the Forth language.
   83: @end direntry
   84: @c The Texinfo manual also recommends doing this, but for Gforth it may
   85: @c  not make much sense
   86: @c @dircategory Individual utilities
   87: @c @direntry
   88: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   89: @c @end direntry
   90: 
   91: @titlepage
   92: @title Gforth
   93: @subtitle for version @value{VERSION}, @value{UPDATED}
   94: @author Neal Crook
   95: @author Anton Ertl
   96: @author David Kuehling
   97: @author Bernd Paysan
   98: @author Jens Wilke
   99: @page
  100: @vskip 0pt plus 1filll
  101: @insertcopying
  102: @end titlepage
  103: 
  104: @contents
  105: 
  106: @ifnottex
  107: @node Top, Goals, (dir), (dir)
  108: @top Gforth
  109: 
  110: @insertcopying
  111: @end ifnottex
  112: 
  113: @menu
  114: * Goals::                       About the Gforth Project
  115: * Gforth Environment::          Starting (and exiting) Gforth
  116: * Tutorial::                    Hands-on Forth Tutorial
  117: * Introduction::                An introduction to ANS Forth
  118: * Words::                       Forth words available in Gforth
  119: * Error messages::              How to interpret them
  120: * Tools::                       Programming tools
  121: * ANS conformance::             Implementation-defined options etc.
  122: * Standard vs Extensions::      Should I use extensions?
  123: * Model::                       The abstract machine of Gforth
  124: * Integrating Gforth::          Forth as scripting language for applications
  125: * Emacs and Gforth::            The Gforth Mode
  126: * Image Files::                 @code{.fi} files contain compiled code
  127: * Engine::                      The inner interpreter and the primitives
  128: * Cross Compiler::              The Cross Compiler
  129: * Bugs::                        How to report them
  130: * Origin::                      Authors and ancestors of Gforth
  131: * Forth-related information::   Books and places to look on the WWW
  132: * Licenses::                    
  133: * Word Index::                  An item for each Forth word
  134: * Concept Index::               A menu covering many topics
  135: 
  136: @detailmenu
  137:  --- The Detailed Node Listing ---
  138: 
  139: Gforth Environment
  140: 
  141: * Invoking Gforth::             Getting in
  142: * Leaving Gforth::              Getting out
  143: * Command-line editing::        
  144: * Environment variables::       that affect how Gforth starts up
  145: * Gforth Files::                What gets installed and where
  146: * Gforth in pipes::             
  147: * Startup speed::               When 35ms is not fast enough ...
  148: 
  149: Forth Tutorial
  150: 
  151: * Starting Gforth Tutorial::    
  152: * Syntax Tutorial::             
  153: * Crash Course Tutorial::       
  154: * Stack Tutorial::              
  155: * Arithmetics Tutorial::        
  156: * Stack Manipulation Tutorial::  
  157: * Using files for Forth code Tutorial::  
  158: * Comments Tutorial::           
  159: * Colon Definitions Tutorial::  
  160: * Decompilation Tutorial::      
  161: * Stack-Effect Comments Tutorial::  
  162: * Types Tutorial::              
  163: * Factoring Tutorial::          
  164: * Designing the stack effect Tutorial::  
  165: * Local Variables Tutorial::    
  166: * Conditional execution Tutorial::  
  167: * Flags and Comparisons Tutorial::  
  168: * General Loops Tutorial::      
  169: * Counted loops Tutorial::      
  170: * Recursion Tutorial::          
  171: * Leaving definitions or loops Tutorial::  
  172: * Return Stack Tutorial::       
  173: * Memory Tutorial::             
  174: * Characters and Strings Tutorial::  
  175: * Alignment Tutorial::          
  176: * Files Tutorial::              
  177: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  178: * Execution Tokens Tutorial::   
  179: * Exceptions Tutorial::         
  180: * Defining Words Tutorial::     
  181: * Arrays and Records Tutorial::  
  182: * POSTPONE Tutorial::           
  183: * Literal Tutorial::            
  184: * Advanced macros Tutorial::    
  185: * Compilation Tokens Tutorial::  
  186: * Wordlists and Search Order Tutorial::  
  187: 
  188: An Introduction to ANS Forth
  189: 
  190: * Introducing the Text Interpreter::  
  191: * Stacks and Postfix notation::  
  192: * Your first definition::       
  193: * How does that work?::         
  194: * Forth is written in Forth::   
  195: * Review - elements of a Forth system::  
  196: * Where to go next::            
  197: * Exercises::                   
  198: 
  199: Forth Words
  200: 
  201: * Notation::                    
  202: * Case insensitivity::          
  203: * Comments::                    
  204: * Boolean Flags::               
  205: * Arithmetic::                  
  206: * Stack Manipulation::          
  207: * Memory::                      
  208: * Control Structures::          
  209: * Defining Words::              
  210: * Interpretation and Compilation Semantics::  
  211: * Tokens for Words::            
  212: * Compiling words::             
  213: * The Text Interpreter::        
  214: * The Input Stream::            
  215: * Word Lists::                  
  216: * Environmental Queries::       
  217: * Files::                       
  218: * Blocks::                      
  219: * Other I/O::                   
  220: * Locals::                      
  221: * Structures::                  
  222: * Object-oriented Forth::       
  223: * Programming Tools::           
  224: * Assembler and Code Words::    
  225: * Threading Words::             
  226: * Passing Commands to the OS::  
  227: * Keeping track of Time::       
  228: * Miscellaneous Words::         
  229: 
  230: Arithmetic
  231: 
  232: * Single precision::            
  233: * Double precision::            Double-cell integer arithmetic
  234: * Bitwise operations::          
  235: * Numeric comparison::          
  236: * Mixed precision::             Operations with single and double-cell integers
  237: * Floating Point::              
  238: 
  239: Stack Manipulation
  240: 
  241: * Data stack::                  
  242: * Floating point stack::        
  243: * Return stack::                
  244: * Locals stack::                
  245: * Stack pointer manipulation::  
  246: 
  247: Memory
  248: 
  249: * Memory model::                
  250: * Dictionary allocation::       
  251: * Heap Allocation::             
  252: * Memory Access::               
  253: * Address arithmetic::          
  254: * Memory Blocks::               
  255: 
  256: Control Structures
  257: 
  258: * Selection::                   IF ... ELSE ... ENDIF
  259: * Simple Loops::                BEGIN ...
  260: * Counted Loops::               DO
  261: * Arbitrary control structures::  
  262: * Calls and returns::           
  263: * Exception Handling::          
  264: 
  265: Defining Words
  266: 
  267: * CREATE::                      
  268: * Variables::                   Variables and user variables
  269: * Constants::                   
  270: * Values::                      Initialised variables
  271: * Colon Definitions::           
  272: * Anonymous Definitions::       Definitions without names
  273: * Supplying names::             Passing definition names as strings
  274: * User-defined Defining Words::  
  275: * Deferred words::              Allow forward references
  276: * Aliases::                     
  277: 
  278: User-defined Defining Words
  279: 
  280: * CREATE..DOES> applications::  
  281: * CREATE..DOES> details::       
  282: * Advanced does> usage example::  
  283: * @code{Const-does>}::          
  284: 
  285: Interpretation and Compilation Semantics
  286: 
  287: * Combined words::              
  288: 
  289: Tokens for Words
  290: 
  291: * Execution token::             represents execution/interpretation semantics
  292: * Compilation token::           represents compilation semantics
  293: * Name token::                  represents named words
  294: 
  295: Compiling words
  296: 
  297: * Literals::                    Compiling data values
  298: * Macros::                      Compiling words
  299: 
  300: The Text Interpreter
  301: 
  302: * Input Sources::               
  303: * Number Conversion::           
  304: * Interpret/Compile states::    
  305: * Interpreter Directives::      
  306: 
  307: Word Lists
  308: 
  309: * Vocabularies::                
  310: * Why use word lists?::         
  311: * Word list example::           
  312: 
  313: Files
  314: 
  315: * Forth source files::          
  316: * General files::               
  317: * Search Paths::                
  318: 
  319: Search Paths
  320: 
  321: * Source Search Paths::         
  322: * General Search Paths::        
  323: 
  324: Other I/O
  325: 
  326: * Simple numeric output::       Predefined formats
  327: * Formatted numeric output::    Formatted (pictured) output
  328: * String Formats::              How Forth stores strings in memory
  329: * Displaying characters and strings::  Other stuff
  330: * Input::                       Input
  331: * Pipes::                       How to create your own pipes
  332: 
  333: Locals
  334: 
  335: * Gforth locals::               
  336: * ANS Forth locals::            
  337: 
  338: Gforth locals
  339: 
  340: * Where are locals visible by name?::  
  341: * How long do locals live?::    
  342: * Locals programming style::    
  343: * Locals implementation::       
  344: 
  345: Structures
  346: 
  347: * Why explicit structure support?::  
  348: * Structure Usage::             
  349: * Structure Naming Convention::  
  350: * Structure Implementation::    
  351: * Structure Glossary::          
  352: 
  353: Object-oriented Forth
  354: 
  355: * Why object-oriented programming?::  
  356: * Object-Oriented Terminology::  
  357: * Objects::                     
  358: * OOF::                         
  359: * Mini-OOF::                    
  360: * Comparison with other object models::  
  361: 
  362: The @file{objects.fs} model
  363: 
  364: * Properties of the Objects model::  
  365: * Basic Objects Usage::         
  366: * The Objects base class::      
  367: * Creating objects::            
  368: * Object-Oriented Programming Style::  
  369: * Class Binding::               
  370: * Method conveniences::         
  371: * Classes and Scoping::         
  372: * Dividing classes::            
  373: * Object Interfaces::           
  374: * Objects Implementation::      
  375: * Objects Glossary::            
  376: 
  377: The @file{oof.fs} model
  378: 
  379: * Properties of the OOF model::  
  380: * Basic OOF Usage::             
  381: * The OOF base class::          
  382: * Class Declaration::           
  383: * Class Implementation::        
  384: 
  385: The @file{mini-oof.fs} model
  386: 
  387: * Basic Mini-OOF Usage::        
  388: * Mini-OOF Example::            
  389: * Mini-OOF Implementation::     
  390: 
  391: Programming Tools
  392: 
  393: * Examining::                   
  394: * Forgetting words::            
  395: * Debugging::                   Simple and quick.
  396: * Assertions::                  Making your programs self-checking.
  397: * Singlestep Debugger::         Executing your program word by word.
  398: 
  399: Assembler and Code Words
  400: 
  401: * Code and ;code::              
  402: * Common Assembler::            Assembler Syntax
  403: * Common Disassembler::         
  404: * 386 Assembler::               Deviations and special cases
  405: * Alpha Assembler::             Deviations and special cases
  406: * MIPS assembler::              Deviations and special cases
  407: * Other assemblers::            How to write them
  408: 
  409: Tools
  410: 
  411: * ANS Report::                  Report the words used, sorted by wordset.
  412: 
  413: ANS conformance
  414: 
  415: * The Core Words::              
  416: * The optional Block word set::  
  417: * The optional Double Number word set::  
  418: * The optional Exception word set::  
  419: * The optional Facility word set::  
  420: * The optional File-Access word set::  
  421: * The optional Floating-Point word set::  
  422: * The optional Locals word set::  
  423: * The optional Memory-Allocation word set::  
  424: * The optional Programming-Tools word set::  
  425: * The optional Search-Order word set::  
  426: 
  427: The Core Words
  428: 
  429: * core-idef::                   Implementation Defined Options                   
  430: * core-ambcond::                Ambiguous Conditions                
  431: * core-other::                  Other System Documentation                  
  432: 
  433: The optional Block word set
  434: 
  435: * block-idef::                  Implementation Defined Options
  436: * block-ambcond::               Ambiguous Conditions               
  437: * block-other::                 Other System Documentation                 
  438: 
  439: The optional Double Number word set
  440: 
  441: * double-ambcond::              Ambiguous Conditions              
  442: 
  443: The optional Exception word set
  444: 
  445: * exception-idef::              Implementation Defined Options              
  446: 
  447: The optional Facility word set
  448: 
  449: * facility-idef::               Implementation Defined Options               
  450: * facility-ambcond::            Ambiguous Conditions            
  451: 
  452: The optional File-Access word set
  453: 
  454: * file-idef::                   Implementation Defined Options
  455: * file-ambcond::                Ambiguous Conditions                
  456: 
  457: The optional Floating-Point word set
  458: 
  459: * floating-idef::               Implementation Defined Options
  460: * floating-ambcond::            Ambiguous Conditions            
  461: 
  462: The optional Locals word set
  463: 
  464: * locals-idef::                 Implementation Defined Options                 
  465: * locals-ambcond::              Ambiguous Conditions              
  466: 
  467: The optional Memory-Allocation word set
  468: 
  469: * memory-idef::                 Implementation Defined Options                 
  470: 
  471: The optional Programming-Tools word set
  472: 
  473: * programming-idef::            Implementation Defined Options            
  474: * programming-ambcond::         Ambiguous Conditions         
  475: 
  476: The optional Search-Order word set
  477: 
  478: * search-idef::                 Implementation Defined Options                 
  479: * search-ambcond::              Ambiguous Conditions              
  480: 
  481: Emacs and Gforth
  482: 
  483: * Installing gforth.el::        Making Emacs aware of Forth.
  484: * Emacs Tags::                  Viewing the source of a word in Emacs.
  485: * Hilighting::                  Making Forth code look prettier.
  486: * Auto-Indentation::            Customizing auto-indentation.
  487: * Blocks Files::                Reading and writing blocks files.
  488: 
  489: Image Files
  490: 
  491: * Image Licensing Issues::      Distribution terms for images.
  492: * Image File Background::       Why have image files?
  493: * Non-Relocatable Image Files::  don't always work.
  494: * Data-Relocatable Image Files::  are better.
  495: * Fully Relocatable Image Files::  better yet.
  496: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  497: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  498: * Modifying the Startup Sequence::  and turnkey applications.
  499: 
  500: Fully Relocatable Image Files
  501: 
  502: * gforthmi::                    The normal way
  503: * cross.fs::                    The hard way
  504: 
  505: Engine
  506: 
  507: * Portability::                 
  508: * Threading::                   
  509: * Primitives::                  
  510: * Performance::                 
  511: 
  512: Threading
  513: 
  514: * Scheduling::                  
  515: * Direct or Indirect Threaded?::  
  516: * Dynamic Superinstructions::   
  517: * DOES>::                       
  518: 
  519: Primitives
  520: 
  521: * Automatic Generation::        
  522: * TOS Optimization::            
  523: * Produced code::               
  524: 
  525: Cross Compiler
  526: 
  527: * Using the Cross Compiler::    
  528: * How the Cross Compiler Works::  
  529: 
  530: Licenses
  531: 
  532: * GNU Free Documentation License::  License for copying this manual.
  533: * Copying::                         GPL (for copying this software).
  534: 
  535: @end detailmenu
  536: @end menu
  537: 
  538: @c ----------------------------------------------------------
  539: @iftex
  540: @unnumbered Preface
  541: @cindex Preface
  542: This manual documents Gforth. Some introductory material is provided for
  543: readers who are unfamiliar with Forth or who are migrating to Gforth
  544: from other Forth compilers. However, this manual is primarily a
  545: reference manual.
  546: @end iftex
  547: 
  548: @comment TODO much more blurb here.
  549: 
  550: @c ******************************************************************
  551: @node Goals, Gforth Environment, Top, Top
  552: @comment node-name,     next,           previous, up
  553: @chapter Goals of Gforth
  554: @cindex goals of the Gforth project
  555: The goal of the Gforth Project is to develop a standard model for
  556: ANS Forth. This can be split into several subgoals:
  557: 
  558: @itemize @bullet
  559: @item
  560: Gforth should conform to the ANS Forth Standard.
  561: @item
  562: It should be a model, i.e. it should define all the
  563: implementation-dependent things.
  564: @item
  565: It should become standard, i.e. widely accepted and used. This goal
  566: is the most difficult one.
  567: @end itemize
  568: 
  569: To achieve these goals Gforth should be
  570: @itemize @bullet
  571: @item
  572: Similar to previous models (fig-Forth, F83)
  573: @item
  574: Powerful. It should provide for all the things that are considered
  575: necessary today and even some that are not yet considered necessary.
  576: @item
  577: Efficient. It should not get the reputation of being exceptionally
  578: slow.
  579: @item
  580: Free.
  581: @item
  582: Available on many machines/easy to port.
  583: @end itemize
  584: 
  585: Have we achieved these goals? Gforth conforms to the ANS Forth
  586: standard. It may be considered a model, but we have not yet documented
  587: which parts of the model are stable and which parts we are likely to
  588: change. It certainly has not yet become a de facto standard, but it
  589: appears to be quite popular. It has some similarities to and some
  590: differences from previous models. It has some powerful features, but not
  591: yet everything that we envisioned. We certainly have achieved our
  592: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  593: the bar was raised when the major commercial Forth vendors switched to
  594: native code compilers.}.  It is free and available on many machines.
  595: 
  596: @c ******************************************************************
  597: @node Gforth Environment, Tutorial, Goals, Top
  598: @chapter Gforth Environment
  599: @cindex Gforth environment
  600: 
  601: Note: ultimately, the Gforth man page will be auto-generated from the
  602: material in this chapter.
  603: 
  604: @menu
  605: * Invoking Gforth::             Getting in
  606: * Leaving Gforth::              Getting out
  607: * Command-line editing::        
  608: * Environment variables::       that affect how Gforth starts up
  609: * Gforth Files::                What gets installed and where
  610: * Gforth in pipes::             
  611: * Startup speed::               When 35ms is not fast enough ...
  612: @end menu
  613: 
  614: For related information about the creation of images see @ref{Image Files}.
  615: 
  616: @comment ----------------------------------------------
  617: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  618: @section Invoking Gforth
  619: @cindex invoking Gforth
  620: @cindex running Gforth
  621: @cindex command-line options
  622: @cindex options on the command line
  623: @cindex flags on the command line
  624: 
  625: Gforth is made up of two parts; an executable ``engine'' (named
  626: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  627: will usually just say @code{gforth} -- this automatically loads the
  628: default image file @file{gforth.fi}. In many other cases the default
  629: Gforth image will be invoked like this:
  630: @example
  631: gforth [file | -e forth-code] ...
  632: @end example
  633: @noindent
  634: This interprets the contents of the files and the Forth code in the order they
  635: are given.
  636: 
  637: In addition to the @command{gforth} engine, there is also an engine
  638: called @command{gforth-fast}, which is faster, but gives less
  639: informative error messages (@pxref{Error messages}) and may catch some
  640: stack underflows later or not at all.  You should use it for debugged,
  641: performance-critical programs.
  642: 
  643: Moreover, there is an engine called @command{gforth-itc}, which is
  644: useful in some backwards-compatibility situations (@pxref{Direct or
  645: Indirect Threaded?}).
  646: 
  647: In general, the command line looks like this:
  648: 
  649: @example
  650: gforth[-fast] [engine options] [image options]
  651: @end example
  652: 
  653: The engine options must come before the rest of the command
  654: line. They are:
  655: 
  656: @table @code
  657: @cindex -i, command-line option
  658: @cindex --image-file, command-line option
  659: @item --image-file @i{file}
  660: @itemx -i @i{file}
  661: Loads the Forth image @i{file} instead of the default
  662: @file{gforth.fi} (@pxref{Image Files}).
  663: 
  664: @cindex --appl-image, command-line option
  665: @item --appl-image @i{file}
  666: Loads the image @i{file} and leaves all further command-line arguments
  667: to the image (instead of processing them as engine options).  This is
  668: useful for building executable application images on Unix, built with
  669: @code{gforthmi --application ...}.
  670: 
  671: @cindex --path, command-line option
  672: @cindex -p, command-line option
  673: @item --path @i{path}
  674: @itemx -p @i{path}
  675: Uses @i{path} for searching the image file and Forth source code files
  676: instead of the default in the environment variable @code{GFORTHPATH} or
  677: the path specified at installation time (e.g.,
  678: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  679: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  680: 
  681: @cindex --dictionary-size, command-line option
  682: @cindex -m, command-line option
  683: @cindex @i{size} parameters for command-line options
  684: @cindex size of the dictionary and the stacks
  685: @item --dictionary-size @i{size}
  686: @itemx -m @i{size}
  687: Allocate @i{size} space for the Forth dictionary space instead of
  688: using the default specified in the image (typically 256K). The
  689: @i{size} specification for this and subsequent options consists of
  690: an integer and a unit (e.g.,
  691: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  692: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  693: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  694: @code{e} is used.
  695: 
  696: @cindex --data-stack-size, command-line option
  697: @cindex -d, command-line option
  698: @item --data-stack-size @i{size}
  699: @itemx -d @i{size}
  700: Allocate @i{size} space for the data stack instead of using the
  701: default specified in the image (typically 16K).
  702: 
  703: @cindex --return-stack-size, command-line option
  704: @cindex -r, command-line option
  705: @item --return-stack-size @i{size}
  706: @itemx -r @i{size}
  707: Allocate @i{size} space for the return stack instead of using the
  708: default specified in the image (typically 15K).
  709: 
  710: @cindex --fp-stack-size, command-line option
  711: @cindex -f, command-line option
  712: @item --fp-stack-size @i{size}
  713: @itemx -f @i{size}
  714: Allocate @i{size} space for the floating point stack instead of
  715: using the default specified in the image (typically 15.5K). In this case
  716: the unit specifier @code{e} refers to floating point numbers.
  717: 
  718: @cindex --locals-stack-size, command-line option
  719: @cindex -l, command-line option
  720: @item --locals-stack-size @i{size}
  721: @itemx -l @i{size}
  722: Allocate @i{size} space for the locals stack instead of using the
  723: default specified in the image (typically 14.5K).
  724: 
  725: @cindex -h, command-line option
  726: @cindex --help, command-line option
  727: @item --help
  728: @itemx -h
  729: Print a message about the command-line options
  730: 
  731: @cindex -v, command-line option
  732: @cindex --version, command-line option
  733: @item --version
  734: @itemx -v
  735: Print version and exit
  736: 
  737: @cindex --debug, command-line option
  738: @item --debug
  739: Print some information useful for debugging on startup.
  740: 
  741: @cindex --offset-image, command-line option
  742: @item --offset-image
  743: Start the dictionary at a slightly different position than would be used
  744: otherwise (useful for creating data-relocatable images,
  745: @pxref{Data-Relocatable Image Files}).
  746: 
  747: @cindex --no-offset-im, command-line option
  748: @item --no-offset-im
  749: Start the dictionary at the normal position.
  750: 
  751: @cindex --clear-dictionary, command-line option
  752: @item --clear-dictionary
  753: Initialize all bytes in the dictionary to 0 before loading the image
  754: (@pxref{Data-Relocatable Image Files}).
  755: 
  756: @cindex --die-on-signal, command-line-option
  757: @item --die-on-signal
  758: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  759: or the segmentation violation SIGSEGV) by translating it into a Forth
  760: @code{THROW}. With this option, Gforth exits if it receives such a
  761: signal. This option is useful when the engine and/or the image might be
  762: severely broken (such that it causes another signal before recovering
  763: from the first); this option avoids endless loops in such cases.
  764: 
  765: @cindex --no-dynamic, command-line option
  766: @cindex --dynamic, command-line option
  767: @item --no-dynamic
  768: @item --dynamic
  769: Disable or enable dynamic superinstructions with replication
  770: (@pxref{Dynamic Superinstructions}).
  771: 
  772: @cindex --no-super, command-line option
  773: @item --no-super
  774: Disable dynamic superinstructions, use just dynamic replication; this is
  775: useful if you want to patch threaded code (@pxref{Dynamic
  776: Superinstructions}).
  777: 
  778: @cindex --ss-number, command-line option
  779: @item --ss-number=@var{N}
  780: Use only the first @var{N} static superinstructions compiled into the
  781: engine (default: use them all; note that only @code{gforth-fast} has
  782: any).  This option is useful for measuring the performance impact of
  783: static superinstructions.
  784: 
  785: @cindex --ss-min-..., command-line options
  786: @item --ss-min-codesize
  787: @item --ss-min-ls
  788: @item --ss-min-lsu
  789: @item --ss-min-nexts
  790: Use specified metric for determining the cost of a primitive or static
  791: superinstruction for static superinstruction selection.  @code{Codesize}
  792: is the native code size of the primive or static superinstruction,
  793: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  794: loads, stores, and updates, and @code{nexts} is the number of dispatches
  795: (not taking dynamic superinstructions into account), i.e. every
  796: primitive or static superinstruction has cost 1. Default:
  797: @code{codesize} if you use dynamic code generation, otherwise
  798: @code{nexts}.
  799: 
  800: @cindex --ss-greedy, command-line option
  801: @item --ss-greedy
  802: This option is useful for measuring the performance impact of static
  803: superinstructions.  By default, an optimal shortest-path algorithm is
  804: used for selecting static superinstructions.  With @option{--ss-greedy}
  805: this algorithm is modified to assume that anything after the static
  806: superinstruction currently under consideration is not combined into
  807: static superinstructions.  With @option{--ss-min-nexts} this produces
  808: the same result as a greedy algorithm that always selects the longest
  809: superinstruction available at the moment.  E.g., if there are
  810: superinstructions AB and BCD, then for the sequence A B C D the optimal
  811: algorithm will select A BCD and the greedy algorithm will select AB C D.
  812: 
  813: @cindex --print-metrics, command-line option
  814: @item --print-metrics
  815: Prints some metrics used during static superinstruction selection:
  816: @code{code size} is the actual size of the dynamically generated code.
  817: @code{Metric codesize} is the sum of the codesize metrics as seen by
  818: static superinstruction selection; there is a difference from @code{code
  819: size}, because not all primitives and static superinstructions are
  820: compiled into dynamically generated code, and because of markers.  The
  821: other metrics correspond to the @option{ss-min-...} options.  This
  822: option is useful for evaluating the effects of the @option{--ss-...}
  823: options.
  824: 
  825: @end table
  826: 
  827: @cindex loading files at startup
  828: @cindex executing code on startup
  829: @cindex batch processing with Gforth
  830: As explained above, the image-specific command-line arguments for the
  831: default image @file{gforth.fi} consist of a sequence of filenames and
  832: @code{-e @var{forth-code}} options that are interpreted in the sequence
  833: in which they are given. The @code{-e @var{forth-code}} or
  834: @code{--evaluate @var{forth-code}} option evaluates the Forth
  835: code. This option takes only one argument; if you want to evaluate more
  836: Forth words, you have to quote them or use @code{-e} several times. To exit
  837: after processing the command line (instead of entering interactive mode)
  838: append @code{-e bye} to the command line.
  839: 
  840: @cindex versions, invoking other versions of Gforth
  841: If you have several versions of Gforth installed, @code{gforth} will
  842: invoke the version that was installed last. @code{gforth-@i{version}}
  843: invokes a specific version. If your environment contains the variable
  844: @code{GFORTHPATH}, you may want to override it by using the
  845: @code{--path} option.
  846: 
  847: Not yet implemented:
  848: On startup the system first executes the system initialization file
  849: (unless the option @code{--no-init-file} is given; note that the system
  850: resulting from using this option may not be ANS Forth conformant). Then
  851: the user initialization file @file{.gforth.fs} is executed, unless the
  852: option @code{--no-rc} is given; this file is searched for in @file{.},
  853: then in @file{~}, then in the normal path (see above).
  854: 
  855: 
  856: 
  857: @comment ----------------------------------------------
  858: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  859: @section Leaving Gforth
  860: @cindex Gforth - leaving
  861: @cindex leaving Gforth
  862: 
  863: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  864: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  865: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  866: data are discarded.  For ways of saving the state of the system before
  867: leaving Gforth see @ref{Image Files}.
  868: 
  869: doc-bye
  870: 
  871: 
  872: @comment ----------------------------------------------
  873: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  874: @section Command-line editing
  875: @cindex command-line editing
  876: 
  877: Gforth maintains a history file that records every line that you type to
  878: the text interpreter. This file is preserved between sessions, and is
  879: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  880: repeatedly you can recall successively older commands from this (or
  881: previous) session(s). The full list of command-line editing facilities is:
  882: 
  883: @itemize @bullet
  884: @item
  885: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  886: commands from the history buffer.
  887: @item
  888: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  889: from the history buffer.
  890: @item
  891: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  892: @item
  893: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  894: @item
  895: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  896: closing up the line.
  897: @item
  898: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  899: @item
  900: @kbd{Ctrl-a} to move the cursor to the start of the line.
  901: @item
  902: @kbd{Ctrl-e} to move the cursor to the end of the line.
  903: @item
  904: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  905: line.
  906: @item
  907: @key{TAB} to step through all possible full-word completions of the word
  908: currently being typed.
  909: @item
  910: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  911: using @code{bye}). 
  912: @item
  913: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  914: character under the cursor.
  915: @end itemize
  916: 
  917: When editing, displayable characters are inserted to the left of the
  918: cursor position; the line is always in ``insert'' (as opposed to
  919: ``overstrike'') mode.
  920: 
  921: @cindex history file
  922: @cindex @file{.gforth-history}
  923: On Unix systems, the history file is @file{~/.gforth-history} by
  924: default@footnote{i.e. it is stored in the user's home directory.}. You
  925: can find out the name and location of your history file using:
  926: 
  927: @example 
  928: history-file type \ Unix-class systems
  929: 
  930: history-file type \ Other systems
  931: history-dir  type
  932: @end example
  933: 
  934: If you enter long definitions by hand, you can use a text editor to
  935: paste them out of the history file into a Forth source file for reuse at
  936: a later time.
  937: 
  938: Gforth never trims the size of the history file, so you should do this
  939: periodically, if necessary.
  940: 
  941: @comment this is all defined in history.fs
  942: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  943: @comment chosen?
  944: 
  945: 
  946: @comment ----------------------------------------------
  947: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  948: @section Environment variables
  949: @cindex environment variables
  950: 
  951: Gforth uses these environment variables:
  952: 
  953: @itemize @bullet
  954: @item
  955: @cindex @code{GFORTHHIST} -- environment variable
  956: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
  957: open/create the history file, @file{.gforth-history}. Default:
  958: @code{$HOME}.
  959: 
  960: @item
  961: @cindex @code{GFORTHPATH} -- environment variable
  962: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
  963: for Forth source-code files.
  964: 
  965: @item
  966: @cindex @code{GFORTH} -- environment variable
  967: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
  968: 
  969: @item
  970: @cindex @code{GFORTHD} -- environment variable
  971: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
  972: 
  973: @item
  974: @cindex @code{TMP}, @code{TEMP} - environment variable
  975: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
  976: location for the history file.
  977: @end itemize
  978: 
  979: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
  980: @comment mentioning these.
  981: 
  982: All the Gforth environment variables default to sensible values if they
  983: are not set.
  984: 
  985: 
  986: @comment ----------------------------------------------
  987: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
  988: @section Gforth files
  989: @cindex Gforth files
  990: 
  991: When you install Gforth on a Unix system, it installs files in these
  992: locations by default:
  993: 
  994: @itemize @bullet
  995: @item
  996: @file{/usr/local/bin/gforth}
  997: @item
  998: @file{/usr/local/bin/gforthmi}
  999: @item
 1000: @file{/usr/local/man/man1/gforth.1} - man page.
 1001: @item
 1002: @file{/usr/local/info} - the Info version of this manual.
 1003: @item
 1004: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1005: @item
 1006: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1007: @item
 1008: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1009: @item
 1010: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1011: @end itemize
 1012: 
 1013: You can select different places for installation by using
 1014: @code{configure} options (listed with @code{configure --help}).
 1015: 
 1016: @comment ----------------------------------------------
 1017: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1018: @section Gforth in pipes
 1019: @cindex pipes, Gforth as part of
 1020: 
 1021: Gforth can be used in pipes created elsewhere (described here).  It can
 1022: also create pipes on its own (@pxref{Pipes}).
 1023: 
 1024: @cindex input from pipes
 1025: If you pipe into Gforth, your program should read with @code{read-file}
 1026: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1027: @code{Key} does not recognize the end of input.  Words like
 1028: @code{accept} echo the input and are therefore usually not useful for
 1029: reading from a pipe.  You have to invoke the Forth program with an OS
 1030: command-line option, as you have no chance to use the Forth command line
 1031: (the text interpreter would try to interpret the pipe input).
 1032: 
 1033: @cindex output in pipes
 1034: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1035: 
 1036: @cindex silent exiting from Gforth
 1037: When you write to a pipe that has been closed at the other end, Gforth
 1038: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1039: into the exception @code{broken-pipe-error}.  If your application does
 1040: not catch that exception, the system catches it and exits, usually
 1041: silently (unless you were working on the Forth command line; then it
 1042: prints an error message and exits).  This is usually the desired
 1043: behaviour.
 1044: 
 1045: If you do not like this behaviour, you have to catch the exception
 1046: yourself, and react to it.
 1047: 
 1048: Here's an example of an invocation of Gforth that is usable in a pipe:
 1049: 
 1050: @example
 1051: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1052:  type repeat ; foo bye"
 1053: @end example
 1054: 
 1055: This example just copies the input verbatim to the output.  A very
 1056: simple pipe containing this example looks like this:
 1057: 
 1058: @example
 1059: cat startup.fs |
 1060: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1061:  type repeat ; foo bye"|
 1062: head
 1063: @end example
 1064: 
 1065: @cindex stderr and pipes
 1066: Pipes involving Gforth's @code{stderr} output do not work.
 1067: 
 1068: @comment ----------------------------------------------
 1069: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1070: @section Startup speed
 1071: @cindex Startup speed
 1072: @cindex speed, startup
 1073: 
 1074: If Gforth is used for CGI scripts or in shell scripts, its startup
 1075: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
 1076: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
 1077: system time.
 1078: 
 1079: If startup speed is a problem, you may consider the following ways to
 1080: improve it; or you may consider ways to reduce the number of startups
 1081: (for example, by using Fast-CGI).
 1082: 
 1083: An easy step that influences Gforth startup speed is the use of the
 1084: @option{--no-dynamic} option; this decreases image loading speed, but
 1085: increases compile-time and run-time.
 1086: 
 1087: Another step to improve startup speed is to statically link Gforth, by
 1088: building it with @code{XLDFLAGS=-static}.  This requires more memory for
 1089: the code and will therefore slow down the first invocation, but
 1090: subsequent invocations avoid the dynamic linking overhead.  Another
 1091: disadvantage is that Gforth won't profit from library upgrades.  As a
 1092: result, @code{gforth-static -e bye} takes about 17.1ms user and
 1093: 8.2ms system time.
 1094: 
 1095: The next step to improve startup speed is to use a non-relocatable image
 1096: (@pxref{Non-Relocatable Image Files}).  You can create this image with
 1097: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
 1098: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
 1099: and a part of the copy-on-write overhead.  The disadvantage is that the
 1100: non-relocatable image does not work if the OS gives Gforth a different
 1101: address for the dictionary, for whatever reason; so you better provide a
 1102: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
 1103: bye} takes about 15.3ms user and 7.5ms system time.
 1104: 
 1105: The final step is to disable dictionary hashing in Gforth.  Gforth
 1106: builds the hash table on startup, which takes much of the startup
 1107: overhead. You can do this by commenting out the @code{include hash.fs}
 1108: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
 1109: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
 1110: The disadvantages are that functionality like @code{table} and
 1111: @code{ekey} is missing and that text interpretation (e.g., compiling)
 1112: now takes much longer. So, you should only use this method if there is
 1113: no significant text interpretation to perform (the script should be
 1114: compiled into the image, amongst other things).  @code{gforth-static -i
 1115: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
 1116: 
 1117: @c ******************************************************************
 1118: @node Tutorial, Introduction, Gforth Environment, Top
 1119: @chapter Forth Tutorial
 1120: @cindex Tutorial
 1121: @cindex Forth Tutorial
 1122: 
 1123: @c Topics from nac's Introduction that could be mentioned:
 1124: @c press <ret> after each line
 1125: @c Prompt
 1126: @c numbers vs. words in dictionary on text interpretation
 1127: @c what happens on redefinition
 1128: @c parsing words (in particular, defining words)
 1129: 
 1130: The difference of this chapter from the Introduction
 1131: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1132: be used while sitting in front of a computer, and covers much more
 1133: material, but does not explain how the Forth system works.
 1134: 
 1135: This tutorial can be used with any ANS-compliant Forth; any
 1136: Gforth-specific features are marked as such and you can skip them if you
 1137: work with another Forth.  This tutorial does not explain all features of
 1138: Forth, just enough to get you started and give you some ideas about the
 1139: facilities available in Forth.  Read the rest of the manual and the
 1140: standard when you are through this.
 1141: 
 1142: The intended way to use this tutorial is that you work through it while
 1143: sitting in front of the console, take a look at the examples and predict
 1144: what they will do, then try them out; if the outcome is not as expected,
 1145: find out why (e.g., by trying out variations of the example), so you
 1146: understand what's going on.  There are also some assignments that you
 1147: should solve.
 1148: 
 1149: This tutorial assumes that you have programmed before and know what,
 1150: e.g., a loop is.
 1151: 
 1152: @c !! explain compat library
 1153: 
 1154: @menu
 1155: * Starting Gforth Tutorial::    
 1156: * Syntax Tutorial::             
 1157: * Crash Course Tutorial::       
 1158: * Stack Tutorial::              
 1159: * Arithmetics Tutorial::        
 1160: * Stack Manipulation Tutorial::  
 1161: * Using files for Forth code Tutorial::  
 1162: * Comments Tutorial::           
 1163: * Colon Definitions Tutorial::  
 1164: * Decompilation Tutorial::      
 1165: * Stack-Effect Comments Tutorial::  
 1166: * Types Tutorial::              
 1167: * Factoring Tutorial::          
 1168: * Designing the stack effect Tutorial::  
 1169: * Local Variables Tutorial::    
 1170: * Conditional execution Tutorial::  
 1171: * Flags and Comparisons Tutorial::  
 1172: * General Loops Tutorial::      
 1173: * Counted loops Tutorial::      
 1174: * Recursion Tutorial::          
 1175: * Leaving definitions or loops Tutorial::  
 1176: * Return Stack Tutorial::       
 1177: * Memory Tutorial::             
 1178: * Characters and Strings Tutorial::  
 1179: * Alignment Tutorial::          
 1180: * Files Tutorial::              
 1181: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1182: * Execution Tokens Tutorial::   
 1183: * Exceptions Tutorial::         
 1184: * Defining Words Tutorial::     
 1185: * Arrays and Records Tutorial::  
 1186: * POSTPONE Tutorial::           
 1187: * Literal Tutorial::            
 1188: * Advanced macros Tutorial::    
 1189: * Compilation Tokens Tutorial::  
 1190: * Wordlists and Search Order Tutorial::  
 1191: @end menu
 1192: 
 1193: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1194: @section Starting Gforth
 1195: @cindex starting Gforth tutorial
 1196: You can start Gforth by typing its name:
 1197: 
 1198: @example
 1199: gforth
 1200: @end example
 1201: 
 1202: That puts you into interactive mode; you can leave Gforth by typing
 1203: @code{bye}.  While in Gforth, you can edit the command line and access
 1204: the command line history with cursor keys, similar to bash.
 1205: 
 1206: 
 1207: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1208: @section Syntax
 1209: @cindex syntax tutorial
 1210: 
 1211: A @dfn{word} is a sequence of arbitrary characters (expcept white
 1212: space).  Words are separated by white space.  E.g., each of the
 1213: following lines contains exactly one word:
 1214: 
 1215: @example
 1216: word
 1217: !@@#$%^&*()
 1218: 1234567890
 1219: 5!a
 1220: @end example
 1221: 
 1222: A frequent beginner's error is to leave away necessary white space,
 1223: resulting in an error like @samp{Undefined word}; so if you see such an
 1224: error, check if you have put spaces wherever necessary.
 1225: 
 1226: @example
 1227: ." hello, world" \ correct
 1228: ."hello, world"  \ gives an "Undefined word" error
 1229: @end example
 1230: 
 1231: Gforth and most other Forth systems ignore differences in case (they are
 1232: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1233: your system is case-sensitive, you may have to type all the examples
 1234: given here in upper case.
 1235: 
 1236: 
 1237: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1238: @section Crash Course
 1239: 
 1240: Type
 1241: 
 1242: @example
 1243: 0 0 !
 1244: here execute
 1245: ' catch >body 20 erase abort
 1246: ' (quit) >body 20 erase
 1247: @end example
 1248: 
 1249: The last two examples are guaranteed to destroy parts of Gforth (and
 1250: most other systems), so you better leave Gforth afterwards (if it has
 1251: not finished by itself).  On some systems you may have to kill gforth
 1252: from outside (e.g., in Unix with @code{kill}).
 1253: 
 1254: Now that you know how to produce crashes (and that there's not much to
 1255: them), let's learn how to produce meaningful programs.
 1256: 
 1257: 
 1258: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1259: @section Stack
 1260: @cindex stack tutorial
 1261: 
 1262: The most obvious feature of Forth is the stack.  When you type in a
 1263: number, it is pushed on the stack.  You can display the content of the
 1264: stack with @code{.s}.
 1265: 
 1266: @example
 1267: 1 2 .s
 1268: 3 .s
 1269: @end example
 1270: 
 1271: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1272: appear in @code{.s} output as they appeared in the input.
 1273: 
 1274: You can print the top of stack element with @code{.}.
 1275: 
 1276: @example
 1277: 1 2 3 . . .
 1278: @end example
 1279: 
 1280: In general, words consume their stack arguments (@code{.s} is an
 1281: exception).
 1282: 
 1283: @assignment
 1284: What does the stack contain after @code{5 6 7 .}?
 1285: @endassignment
 1286: 
 1287: 
 1288: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1289: @section Arithmetics
 1290: @cindex arithmetics tutorial
 1291: 
 1292: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1293: operate on the top two stack items:
 1294: 
 1295: @example
 1296: 2 2 .s
 1297: + .s
 1298: .
 1299: 2 1 - .
 1300: 7 3 mod .
 1301: @end example
 1302: 
 1303: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1304: as in the corresponding infix expression (this is generally the case in
 1305: Forth).
 1306: 
 1307: Parentheses are superfluous (and not available), because the order of
 1308: the words unambiguously determines the order of evaluation and the
 1309: operands:
 1310: 
 1311: @example
 1312: 3 4 + 5 * .
 1313: 3 4 5 * + .
 1314: @end example
 1315: 
 1316: @assignment
 1317: What are the infix expressions corresponding to the Forth code above?
 1318: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1319: known as Postfix or RPN (Reverse Polish Notation).}.
 1320: @endassignment
 1321: 
 1322: To change the sign, use @code{negate}:
 1323: 
 1324: @example
 1325: 2 negate .
 1326: @end example
 1327: 
 1328: @assignment
 1329: Convert -(-3)*4-5 to Forth.
 1330: @endassignment
 1331: 
 1332: @code{/mod} performs both @code{/} and @code{mod}.
 1333: 
 1334: @example
 1335: 7 3 /mod . .
 1336: @end example
 1337: 
 1338: Reference: @ref{Arithmetic}.
 1339: 
 1340: 
 1341: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1342: @section Stack Manipulation
 1343: @cindex stack manipulation tutorial
 1344: 
 1345: Stack manipulation words rearrange the data on the stack.
 1346: 
 1347: @example
 1348: 1 .s drop .s
 1349: 1 .s dup .s drop drop .s
 1350: 1 2 .s over .s drop drop drop
 1351: 1 2 .s swap .s drop drop
 1352: 1 2 3 .s rot .s drop drop drop
 1353: @end example
 1354: 
 1355: These are the most important stack manipulation words.  There are also
 1356: variants that manipulate twice as many stack items:
 1357: 
 1358: @example
 1359: 1 2 3 4 .s 2swap .s 2drop 2drop
 1360: @end example
 1361: 
 1362: Two more stack manipulation words are:
 1363: 
 1364: @example
 1365: 1 2 .s nip .s drop
 1366: 1 2 .s tuck .s 2drop drop
 1367: @end example
 1368: 
 1369: @assignment
 1370: Replace @code{nip} and @code{tuck} with combinations of other stack
 1371: manipulation words.
 1372: 
 1373: @example
 1374: Given:          How do you get:
 1375: 1 2 3           3 2 1           
 1376: 1 2 3           1 2 3 2                 
 1377: 1 2 3           1 2 3 3                 
 1378: 1 2 3           1 3 3           
 1379: 1 2 3           2 1 3           
 1380: 1 2 3 4         4 3 2 1         
 1381: 1 2 3           1 2 3 1 2 3             
 1382: 1 2 3 4         1 2 3 4 1 2             
 1383: 1 2 3
 1384: 1 2 3           1 2 3 4                 
 1385: 1 2 3           1 3             
 1386: @end example
 1387: @endassignment
 1388: 
 1389: @example
 1390: 5 dup * .
 1391: @end example
 1392: 
 1393: @assignment
 1394: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1395: Write a piece of Forth code that expects two numbers on the stack
 1396: (@var{a} and @var{b}, with @var{b} on top) and computes
 1397: @code{(a-b)(a+1)}.
 1398: @endassignment
 1399: 
 1400: Reference: @ref{Stack Manipulation}.
 1401: 
 1402: 
 1403: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1404: @section Using files for Forth code
 1405: @cindex loading Forth code, tutorial
 1406: @cindex files containing Forth code, tutorial
 1407: 
 1408: While working at the Forth command line is convenient for one-line
 1409: examples and short one-off code, you probably want to store your source
 1410: code in files for convenient editing and persistence.  You can use your
 1411: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1412: Gforth}) to create @var{file.fs} and use
 1413: 
 1414: @example
 1415: s" @var{file.fs}" included
 1416: @end example
 1417: 
 1418: to load it into your Forth system.  The file name extension I use for
 1419: Forth files is @samp{.fs}.
 1420: 
 1421: You can easily start Gforth with some files loaded like this:
 1422: 
 1423: @example
 1424: gforth @var{file1.fs} @var{file2.fs}
 1425: @end example
 1426: 
 1427: If an error occurs during loading these files, Gforth terminates,
 1428: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1429: a Gforth command line.  Starting the Forth system every time gives you a
 1430: clean start every time, without interference from the results of earlier
 1431: tries.
 1432: 
 1433: I often put all the tests in a file, then load the code and run the
 1434: tests with
 1435: 
 1436: @example
 1437: gforth @var{code.fs} @var{tests.fs} -e bye
 1438: @end example
 1439: 
 1440: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1441: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1442: restart this command without ado.
 1443: 
 1444: The advantage of this approach is that the tests can be repeated easily
 1445: every time the program ist changed, making it easy to catch bugs
 1446: introduced by the change.
 1447: 
 1448: Reference: @ref{Forth source files}.
 1449: 
 1450: 
 1451: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1452: @section Comments
 1453: @cindex comments tutorial
 1454: 
 1455: @example
 1456: \ That's a comment; it ends at the end of the line
 1457: ( Another comment; it ends here: )  .s
 1458: @end example
 1459: 
 1460: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1461: separated with white space from the following text.
 1462: 
 1463: @example
 1464: \This gives an "Undefined word" error
 1465: @end example
 1466: 
 1467: The first @code{)} ends a comment started with @code{(}, so you cannot
 1468: nest @code{(}-comments; and you cannot comment out text containing a
 1469: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1470: avoid @code{)} in word names.}.
 1471: 
 1472: I use @code{\}-comments for descriptive text and for commenting out code
 1473: of one or more line; I use @code{(}-comments for describing the stack
 1474: effect, the stack contents, or for commenting out sub-line pieces of
 1475: code.
 1476: 
 1477: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1478: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1479: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1480: with @kbd{M-q}.
 1481: 
 1482: Reference: @ref{Comments}.
 1483: 
 1484: 
 1485: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1486: @section Colon Definitions
 1487: @cindex colon definitions, tutorial
 1488: @cindex definitions, tutorial
 1489: @cindex procedures, tutorial
 1490: @cindex functions, tutorial
 1491: 
 1492: are similar to procedures and functions in other programming languages.
 1493: 
 1494: @example
 1495: : squared ( n -- n^2 )
 1496:    dup * ;
 1497: 5 squared .
 1498: 7 squared .
 1499: @end example
 1500: 
 1501: @code{:} starts the colon definition; its name is @code{squared}.  The
 1502: following comment describes its stack effect.  The words @code{dup *}
 1503: are not executed, but compiled into the definition.  @code{;} ends the
 1504: colon definition.
 1505: 
 1506: The newly-defined word can be used like any other word, including using
 1507: it in other definitions:
 1508: 
 1509: @example
 1510: : cubed ( n -- n^3 )
 1511:    dup squared * ;
 1512: -5 cubed .
 1513: : fourth-power ( n -- n^4 )
 1514:    squared squared ;
 1515: 3 fourth-power .
 1516: @end example
 1517: 
 1518: @assignment
 1519: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1520: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1521: test your tests on the originals first).  Don't let the
 1522: @samp{redefined}-Messages spook you, they are just warnings.
 1523: @endassignment
 1524: 
 1525: Reference: @ref{Colon Definitions}.
 1526: 
 1527: 
 1528: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1529: @section Decompilation
 1530: @cindex decompilation tutorial
 1531: @cindex see tutorial
 1532: 
 1533: You can decompile colon definitions with @code{see}:
 1534: 
 1535: @example
 1536: see squared
 1537: see cubed
 1538: @end example
 1539: 
 1540: In Gforth @code{see} shows you a reconstruction of the source code from
 1541: the executable code.  Informations that were present in the source, but
 1542: not in the executable code, are lost (e.g., comments).
 1543: 
 1544: You can also decompile the predefined words:
 1545: 
 1546: @example
 1547: see .
 1548: see +
 1549: @end example
 1550: 
 1551: 
 1552: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1553: @section Stack-Effect Comments
 1554: @cindex stack-effect comments, tutorial
 1555: @cindex --, tutorial
 1556: By convention the comment after the name of a definition describes the
 1557: stack effect: The part in from of the @samp{--} describes the state of
 1558: the stack before the execution of the definition, i.e., the parameters
 1559: that are passed into the colon definition; the part behind the @samp{--}
 1560: is the state of the stack after the execution of the definition, i.e.,
 1561: the results of the definition.  The stack comment only shows the top
 1562: stack items that the definition accesses and/or changes.
 1563: 
 1564: You should put a correct stack effect on every definition, even if it is
 1565: just @code{( -- )}.  You should also add some descriptive comment to
 1566: more complicated words (I usually do this in the lines following
 1567: @code{:}).  If you don't do this, your code becomes unreadable (because
 1568: you have to work through every definition before you can understand
 1569: any).
 1570: 
 1571: @assignment
 1572: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1573: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1574: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1575: are done, you can compare your stack effects to those in this manual
 1576: (@pxref{Word Index}).
 1577: @endassignment
 1578: 
 1579: Sometimes programmers put comments at various places in colon
 1580: definitions that describe the contents of the stack at that place (stack
 1581: comments); i.e., they are like the first part of a stack-effect
 1582: comment. E.g.,
 1583: 
 1584: @example
 1585: : cubed ( n -- n^3 )
 1586:    dup squared  ( n n^2 ) * ;
 1587: @end example
 1588: 
 1589: In this case the stack comment is pretty superfluous, because the word
 1590: is simple enough.  If you think it would be a good idea to add such a
 1591: comment to increase readability, you should also consider factoring the
 1592: word into several simpler words (@pxref{Factoring Tutorial,,
 1593: Factoring}), which typically eliminates the need for the stack comment;
 1594: however, if you decide not to refactor it, then having such a comment is
 1595: better than not having it.
 1596: 
 1597: The names of the stack items in stack-effect and stack comments in the
 1598: standard, in this manual, and in many programs specify the type through
 1599: a type prefix, similar to Fortran and Hungarian notation.  The most
 1600: frequent prefixes are:
 1601: 
 1602: @table @code
 1603: @item n
 1604: signed integer
 1605: @item u
 1606: unsigned integer
 1607: @item c
 1608: character
 1609: @item f
 1610: Boolean flags, i.e. @code{false} or @code{true}.
 1611: @item a-addr,a-
 1612: Cell-aligned address
 1613: @item c-addr,c-
 1614: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1615: @item xt
 1616: Execution token, same size as Cell
 1617: @item w,x
 1618: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1619: 16 bits (depending on your platform and Forth system). A cell is more
 1620: commonly known as machine word, but the term @emph{word} already means
 1621: something different in Forth.
 1622: @item d
 1623: signed double-cell integer
 1624: @item ud
 1625: unsigned double-cell integer
 1626: @item r
 1627: Float (on the FP stack)
 1628: @end table
 1629: 
 1630: You can find a more complete list in @ref{Notation}.
 1631: 
 1632: @assignment
 1633: Write stack-effect comments for all definitions you have written up to
 1634: now.
 1635: @endassignment
 1636: 
 1637: 
 1638: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1639: @section Types
 1640: @cindex types tutorial
 1641: 
 1642: In Forth the names of the operations are not overloaded; so similar
 1643: operations on different types need different names; e.g., @code{+} adds
 1644: integers, and you have to use @code{f+} to add floating-point numbers.
 1645: The following prefixes are often used for related operations on
 1646: different types:
 1647: 
 1648: @table @code
 1649: @item (none)
 1650: signed integer
 1651: @item u
 1652: unsigned integer
 1653: @item c
 1654: character
 1655: @item d
 1656: signed double-cell integer
 1657: @item ud, du
 1658: unsigned double-cell integer
 1659: @item 2
 1660: two cells (not-necessarily double-cell numbers)
 1661: @item m, um
 1662: mixed single-cell and double-cell operations
 1663: @item f
 1664: floating-point (note that in stack comments @samp{f} represents flags,
 1665: and @samp{r} represents FP numbers).
 1666: @end table
 1667: 
 1668: If there are no differences between the signed and the unsigned variant
 1669: (e.g., for @code{+}), there is only the prefix-less variant.
 1670: 
 1671: Forth does not perform type checking, neither at compile time, nor at
 1672: run time.  If you use the wrong oeration, the data are interpreted
 1673: incorrectly:
 1674: 
 1675: @example
 1676: -1 u.
 1677: @end example
 1678: 
 1679: If you have only experience with type-checked languages until now, and
 1680: have heard how important type-checking is, don't panic!  In my
 1681: experience (and that of other Forthers), type errors in Forth code are
 1682: usually easy to find (once you get used to it), the increased vigilance
 1683: of the programmer tends to catch some harder errors in addition to most
 1684: type errors, and you never have to work around the type system, so in
 1685: most situations the lack of type-checking seems to be a win (projects to
 1686: add type checking to Forth have not caught on).
 1687: 
 1688: 
 1689: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1690: @section Factoring
 1691: @cindex factoring tutorial
 1692: 
 1693: If you try to write longer definitions, you will soon find it hard to
 1694: keep track of the stack contents.  Therefore, good Forth programmers
 1695: tend to write only short definitions (e.g., three lines).  The art of
 1696: finding meaningful short definitions is known as factoring (as in
 1697: factoring polynomials).
 1698: 
 1699: Well-factored programs offer additional advantages: smaller, more
 1700: general words, are easier to test and debug and can be reused more and
 1701: better than larger, specialized words.
 1702: 
 1703: So, if you run into difficulties with stack management, when writing
 1704: code, try to define meaningful factors for the word, and define the word
 1705: in terms of those.  Even if a factor contains only two words, it is
 1706: often helpful.
 1707: 
 1708: Good factoring is not easy, and it takes some practice to get the knack
 1709: for it; but even experienced Forth programmers often don't find the
 1710: right solution right away, but only when rewriting the program.  So, if
 1711: you don't come up with a good solution immediately, keep trying, don't
 1712: despair.
 1713: 
 1714: @c example !!
 1715: 
 1716: 
 1717: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1718: @section Designing the stack effect
 1719: @cindex Stack effect design, tutorial
 1720: @cindex design of stack effects, tutorial
 1721: 
 1722: In other languages you can use an arbitrary order of parameters for a
 1723: function; and since there is only one result, you don't have to deal with
 1724: the order of results, either.
 1725: 
 1726: In Forth (and other stack-based languages, e.g., PostScript) the
 1727: parameter and result order of a definition is important and should be
 1728: designed well.  The general guideline is to design the stack effect such
 1729: that the word is simple to use in most cases, even if that complicates
 1730: the implementation of the word.  Some concrete rules are:
 1731: 
 1732: @itemize @bullet
 1733: 
 1734: @item
 1735: Words consume all of their parameters (e.g., @code{.}).
 1736: 
 1737: @item
 1738: If there is a convention on the order of parameters (e.g., from
 1739: mathematics or another programming language), stick with it (e.g.,
 1740: @code{-}).
 1741: 
 1742: @item
 1743: If one parameter usually requires only a short computation (e.g., it is
 1744: a constant), pass it on the top of the stack.  Conversely, parameters
 1745: that usually require a long sequence of code to compute should be passed
 1746: as the bottom (i.e., first) parameter.  This makes the code easier to
 1747: read, because reader does not need to keep track of the bottom item
 1748: through a long sequence of code (or, alternatively, through stack
 1749: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1750: address on top of the stack because it is usually simpler to compute
 1751: than the stored value (often the address is just a variable).
 1752: 
 1753: @item
 1754: Similarly, results that are usually consumed quickly should be returned
 1755: on the top of stack, whereas a result that is often used in long
 1756: computations should be passed as bottom result.  E.g., the file words
 1757: like @code{open-file} return the error code on the top of stack, because
 1758: it is usually consumed quickly by @code{throw}; moreover, the error code
 1759: has to be checked before doing anything with the other results.
 1760: 
 1761: @end itemize
 1762: 
 1763: These rules are just general guidelines, don't lose sight of the overall
 1764: goal to make the words easy to use.  E.g., if the convention rule
 1765: conflicts with the computation-length rule, you might decide in favour
 1766: of the convention if the word will be used rarely, and in favour of the
 1767: computation-length rule if the word will be used frequently (because
 1768: with frequent use the cost of breaking the computation-length rule would
 1769: be quite high, and frequent use makes it easier to remember an
 1770: unconventional order).
 1771: 
 1772: @c example !! structure package
 1773: 
 1774: 
 1775: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1776: @section Local Variables
 1777: @cindex local variables, tutorial
 1778: 
 1779: You can define local variables (@emph{locals}) in a colon definition:
 1780: 
 1781: @example
 1782: : swap @{ a b -- b a @}
 1783:   b a ;
 1784: 1 2 swap .s 2drop
 1785: @end example
 1786: 
 1787: (If your Forth system does not support this syntax, include
 1788: @file{compat/anslocals.fs} first).
 1789: 
 1790: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1791: takes two cells from the stack, puts the top of stack in @code{b} and
 1792: the next stack element in @code{a}.  @code{--} starts a comment ending
 1793: with @code{@}}.  After the locals definition, using the name of the
 1794: local will push its value on the stack.  You can leave the comment
 1795: part (@code{-- b a}) away:
 1796: 
 1797: @example
 1798: : swap ( x1 x2 -- x2 x1 )
 1799:   @{ a b @} b a ;
 1800: @end example
 1801: 
 1802: In Gforth you can have several locals definitions, anywhere in a colon
 1803: definition; in contrast, in a standard program you can have only one
 1804: locals definition per colon definition, and that locals definition must
 1805: be outside any controll structure.
 1806: 
 1807: With locals you can write slightly longer definitions without running
 1808: into stack trouble.  However, I recommend trying to write colon
 1809: definitions without locals for exercise purposes to help you gain the
 1810: essential factoring skills.
 1811: 
 1812: @assignment
 1813: Rewrite your definitions until now with locals
 1814: @endassignment
 1815: 
 1816: Reference: @ref{Locals}.
 1817: 
 1818: 
 1819: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1820: @section Conditional execution
 1821: @cindex conditionals, tutorial
 1822: @cindex if, tutorial
 1823: 
 1824: In Forth you can use control structures only inside colon definitions.
 1825: An @code{if}-structure looks like this:
 1826: 
 1827: @example
 1828: : abs ( n1 -- +n2 )
 1829:     dup 0 < if
 1830:         negate
 1831:     endif ;
 1832: 5 abs .
 1833: -5 abs .
 1834: @end example
 1835: 
 1836: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1837: the following code is performed, otherwise execution continues after the
 1838: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1839: elements and prioduces a flag:
 1840: 
 1841: @example
 1842: 1 2 < .
 1843: 2 1 < .
 1844: 1 1 < .
 1845: @end example
 1846: 
 1847: Actually the standard name for @code{endif} is @code{then}.  This
 1848: tutorial presents the examples using @code{endif}, because this is often
 1849: less confusing for people familiar with other programming languages
 1850: where @code{then} has a different meaning.  If your system does not have
 1851: @code{endif}, define it with
 1852: 
 1853: @example
 1854: : endif postpone then ; immediate
 1855: @end example
 1856: 
 1857: You can optionally use an @code{else}-part:
 1858: 
 1859: @example
 1860: : min ( n1 n2 -- n )
 1861:   2dup < if
 1862:     drop
 1863:   else
 1864:     nip
 1865:   endif ;
 1866: 2 3 min .
 1867: 3 2 min .
 1868: @end example
 1869: 
 1870: @assignment
 1871: Write @code{min} without @code{else}-part (hint: what's the definition
 1872: of @code{nip}?).
 1873: @endassignment
 1874: 
 1875: Reference: @ref{Selection}.
 1876: 
 1877: 
 1878: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1879: @section Flags and Comparisons
 1880: @cindex flags tutorial
 1881: @cindex comparison tutorial
 1882: 
 1883: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1884: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1885: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1886: treated as true flag.
 1887: 
 1888: @example
 1889: false .
 1890: true .
 1891: true hex u. decimal
 1892: @end example
 1893: 
 1894: Comparison words produce canonical flags:
 1895: 
 1896: @example
 1897: 1 1 = .
 1898: 1 0= .
 1899: 0 1 < .
 1900: 0 0 < .
 1901: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1902: -1 1 < .
 1903: @end example
 1904: 
 1905: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 1906: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 1907: these combinations are standard (for details see the standard,
 1908: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 1909: 
 1910: You can use @code{and or xor invert} can be used as operations on
 1911: canonical flags.  Actually they are bitwise operations:
 1912: 
 1913: @example
 1914: 1 2 and .
 1915: 1 2 or .
 1916: 1 3 xor .
 1917: 1 invert .
 1918: @end example
 1919: 
 1920: You can convert a zero/non-zero flag into a canonical flag with
 1921: @code{0<>} (and complement it on the way with @code{0=}).
 1922: 
 1923: @example
 1924: 1 0= .
 1925: 1 0<> .
 1926: @end example
 1927: 
 1928: You can use the all-bits-set feature of canonical flags and the bitwise
 1929: operation of the Boolean operations to avoid @code{if}s:
 1930: 
 1931: @example
 1932: : foo ( n1 -- n2 )
 1933:   0= if
 1934:     14
 1935:   else
 1936:     0
 1937:   endif ;
 1938: 0 foo .
 1939: 1 foo .
 1940: 
 1941: : foo ( n1 -- n2 )
 1942:   0= 14 and ;
 1943: 0 foo .
 1944: 1 foo .
 1945: @end example
 1946: 
 1947: @assignment
 1948: Write @code{min} without @code{if}.
 1949: @endassignment
 1950: 
 1951: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 1952: @ref{Bitwise operations}.
 1953: 
 1954: 
 1955: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 1956: @section General Loops
 1957: @cindex loops, indefinite, tutorial
 1958: 
 1959: The endless loop is the most simple one:
 1960: 
 1961: @example
 1962: : endless ( -- )
 1963:   0 begin
 1964:     dup . 1+
 1965:   again ;
 1966: endless
 1967: @end example
 1968: 
 1969: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 1970: does nothing at run-time, @code{again} jumps back to @code{begin}.
 1971: 
 1972: A loop with one exit at any place looks like this:
 1973: 
 1974: @example
 1975: : log2 ( +n1 -- n2 )
 1976: \ logarithmus dualis of n1>0, rounded down to the next integer
 1977:   assert( dup 0> )
 1978:   2/ 0 begin
 1979:     over 0> while
 1980:       1+ swap 2/ swap
 1981:   repeat
 1982:   nip ;
 1983: 7 log2 .
 1984: 8 log2 .
 1985: @end example
 1986: 
 1987: At run-time @code{while} consumes a flag; if it is 0, execution
 1988: continues behind the @code{repeat}; if the flag is non-zero, execution
 1989: continues behind the @code{while}.  @code{Repeat} jumps back to
 1990: @code{begin}, just like @code{again}.
 1991: 
 1992: In Forth there are many combinations/abbreviations, like @code{1+}.
 1993: However, @code{2/} is not one of them; it shifts its argument right by
 1994: one bit (arithmetic shift right):
 1995: 
 1996: @example
 1997: -5 2 / .
 1998: -5 2/ .
 1999: @end example
 2000: 
 2001: @code{assert(} is no standard word, but you can get it on systems other
 2002: then Gforth by including @file{compat/assert.fs}.  You can see what it
 2003: does by trying
 2004: 
 2005: @example
 2006: 0 log2 .
 2007: @end example
 2008: 
 2009: Here's a loop with an exit at the end:
 2010: 
 2011: @example
 2012: : log2 ( +n1 -- n2 )
 2013: \ logarithmus dualis of n1>0, rounded down to the next integer
 2014:   assert( dup 0 > )
 2015:   -1 begin
 2016:     1+ swap 2/ swap
 2017:     over 0 <=
 2018:   until
 2019:   nip ;
 2020: @end example
 2021: 
 2022: @code{Until} consumes a flag; if it is non-zero, execution continues at
 2023: the @code{begin}, otherwise after the @code{until}.
 2024: 
 2025: @assignment
 2026: Write a definition for computing the greatest common divisor.
 2027: @endassignment
 2028: 
 2029: Reference: @ref{Simple Loops}.
 2030: 
 2031: 
 2032: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2033: @section Counted loops
 2034: @cindex loops, counted, tutorial
 2035: 
 2036: @example
 2037: : ^ ( n1 u -- n )
 2038: \ n = the uth power of u1
 2039:   1 swap 0 u+do
 2040:     over *
 2041:   loop
 2042:   nip ;
 2043: 3 2 ^ .
 2044: 4 3 ^ .
 2045: @end example
 2046: 
 2047: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2048: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2049: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2050: times (or not at all, if @code{u3-u4<0}).
 2051: 
 2052: You can see the stack effect design rules at work in the stack effect of
 2053: the loop start words: Since the start value of the loop is more
 2054: frequently constant than the end value, the start value is passed on
 2055: the top-of-stack.
 2056: 
 2057: You can access the counter of a counted loop with @code{i}:
 2058: 
 2059: @example
 2060: : fac ( u -- u! )
 2061:   1 swap 1+ 1 u+do
 2062:     i *
 2063:   loop ;
 2064: 5 fac .
 2065: 7 fac .
 2066: @end example
 2067: 
 2068: There is also @code{+do}, which expects signed numbers (important for
 2069: deciding whether to enter the loop).
 2070: 
 2071: @assignment
 2072: Write a definition for computing the nth Fibonacci number.
 2073: @endassignment
 2074: 
 2075: You can also use increments other than 1:
 2076: 
 2077: @example
 2078: : up2 ( n1 n2 -- )
 2079:   +do
 2080:     i .
 2081:   2 +loop ;
 2082: 10 0 up2
 2083: 
 2084: : down2 ( n1 n2 -- )
 2085:   -do
 2086:     i .
 2087:   2 -loop ;
 2088: 0 10 down2
 2089: @end example
 2090: 
 2091: Reference: @ref{Counted Loops}.
 2092: 
 2093: 
 2094: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2095: @section Recursion
 2096: @cindex recursion tutorial
 2097: 
 2098: Usually the name of a definition is not visible in the definition; but
 2099: earlier definitions are usually visible:
 2100: 
 2101: @example
 2102: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
 2103: : / ( n1 n2 -- n )
 2104:   dup 0= if
 2105:     -10 throw \ report division by zero
 2106:   endif
 2107:   /           \ old version
 2108: ;
 2109: 1 0 /
 2110: @end example
 2111: 
 2112: For recursive definitions you can use @code{recursive} (non-standard) or
 2113: @code{recurse}:
 2114: 
 2115: @example
 2116: : fac1 ( n -- n! ) recursive
 2117:  dup 0> if
 2118:    dup 1- fac1 *
 2119:  else
 2120:    drop 1
 2121:  endif ;
 2122: 7 fac1 .
 2123: 
 2124: : fac2 ( n -- n! )
 2125:  dup 0> if
 2126:    dup 1- recurse *
 2127:  else
 2128:    drop 1
 2129:  endif ;
 2130: 8 fac2 .
 2131: @end example
 2132: 
 2133: @assignment
 2134: Write a recursive definition for computing the nth Fibonacci number.
 2135: @endassignment
 2136: 
 2137: Reference (including indirect recursion): @xref{Calls and returns}.
 2138: 
 2139: 
 2140: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2141: @section Leaving definitions or loops
 2142: @cindex leaving definitions, tutorial
 2143: @cindex leaving loops, tutorial
 2144: 
 2145: @code{EXIT} exits the current definition right away.  For every counted
 2146: loop that is left in this way, an @code{UNLOOP} has to be performed
 2147: before the @code{EXIT}:
 2148: 
 2149: @c !! real examples
 2150: @example
 2151: : ...
 2152:  ... u+do
 2153:    ... if
 2154:      ... unloop exit
 2155:    endif
 2156:    ...
 2157:  loop
 2158:  ... ;
 2159: @end example
 2160: 
 2161: @code{LEAVE} leaves the innermost counted loop right away:
 2162: 
 2163: @example
 2164: : ...
 2165:  ... u+do
 2166:    ... if
 2167:      ... leave
 2168:    endif
 2169:    ...
 2170:  loop
 2171:  ... ;
 2172: @end example
 2173: 
 2174: @c !! example
 2175: 
 2176: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2177: 
 2178: 
 2179: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2180: @section Return Stack
 2181: @cindex return stack tutorial
 2182: 
 2183: In addition to the data stack Forth also has a second stack, the return
 2184: stack; most Forth systems store the return addresses of procedure calls
 2185: there (thus its name).  Programmers can also use this stack:
 2186: 
 2187: @example
 2188: : foo ( n1 n2 -- )
 2189:  .s
 2190:  >r .s
 2191:  r@@ .
 2192:  >r .s
 2193:  r@@ .
 2194:  r> .
 2195:  r@@ .
 2196:  r> . ;
 2197: 1 2 foo
 2198: @end example
 2199: 
 2200: @code{>r} takes an element from the data stack and pushes it onto the
 2201: return stack; conversely, @code{r>} moves an elementm from the return to
 2202: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2203: on the return stack.
 2204: 
 2205: Forth programmers usually use the return stack for storing data
 2206: temporarily, if using the data stack alone would be too complex, and
 2207: factoring and locals are not an option:
 2208: 
 2209: @example
 2210: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2211:  rot >r rot r> ;
 2212: @end example
 2213: 
 2214: The return address of the definition and the loop control parameters of
 2215: counted loops usually reside on the return stack, so you have to take
 2216: all items, that you have pushed on the return stack in a colon
 2217: definition or counted loop, from the return stack before the definition
 2218: or loop ends.  You cannot access items that you pushed on the return
 2219: stack outside some definition or loop within the definition of loop.
 2220: 
 2221: If you miscount the return stack items, this usually ends in a crash:
 2222: 
 2223: @example
 2224: : crash ( n -- )
 2225:   >r ;
 2226: 5 crash
 2227: @end example
 2228: 
 2229: You cannot mix using locals and using the return stack (according to the
 2230: standard; Gforth has no problem).  However, they solve the same
 2231: problems, so this shouldn't be an issue.
 2232: 
 2233: @assignment
 2234: Can you rewrite any of the definitions you wrote until now in a better
 2235: way using the return stack?
 2236: @endassignment
 2237: 
 2238: Reference: @ref{Return stack}.
 2239: 
 2240: 
 2241: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2242: @section Memory
 2243: @cindex memory access/allocation tutorial
 2244: 
 2245: You can create a global variable @code{v} with
 2246: 
 2247: @example
 2248: variable v ( -- addr )
 2249: @end example
 2250: 
 2251: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2252: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2253: values into this cell and @code{@@} (fetch) to load the value from the
 2254: stack into memory:
 2255: 
 2256: @example
 2257: v .
 2258: 5 v ! .s
 2259: v @@ .
 2260: @end example
 2261: 
 2262: You can see a raw dump of memory with @code{dump}:
 2263: 
 2264: @example
 2265: v 1 cells .s dump
 2266: @end example
 2267: 
 2268: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2269: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2270: also reserve more memory:
 2271: 
 2272: @example
 2273: create v2 20 cells allot
 2274: v2 20 cells dump
 2275: @end example
 2276: 
 2277: creates a word @code{v2} and reserves 20 uninitialized cells; the
 2278: address pushed by @code{v2} points to the start of these 20 cells.  You
 2279: can use address arithmetic to access these cells:
 2280: 
 2281: @example
 2282: 3 v2 5 cells + !
 2283: v2 20 cells dump
 2284: @end example
 2285: 
 2286: You can reserve and initialize memory with @code{,}:
 2287: 
 2288: @example
 2289: create v3
 2290:   5 , 4 , 3 , 2 , 1 ,
 2291: v3 @@ .
 2292: v3 cell+ @@ .
 2293: v3 2 cells + @@ .
 2294: v3 5 cells dump
 2295: @end example
 2296: 
 2297: @assignment
 2298: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2299: @code{u} cells, with the first of these cells at @code{addr}, the next
 2300: one at @code{addr cell+} etc.
 2301: @endassignment
 2302: 
 2303: You can also reserve memory without creating a new word:
 2304: 
 2305: @example
 2306: here 10 cells allot .
 2307: here .
 2308: @end example
 2309: 
 2310: @code{Here} pushes the start address of the memory area.  You should
 2311: store it somewhere, or you will have a hard time finding the memory area
 2312: again.
 2313: 
 2314: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2315: the system's data structures for words etc. on Gforth and most other
 2316: Forth systems.  It is managed like a stack: You can free the memory that
 2317: you have just @code{allot}ed with
 2318: 
 2319: @example
 2320: -10 cells allot
 2321: here .
 2322: @end example
 2323: 
 2324: Note that you cannot do this if you have created a new word in the
 2325: meantime (because then your @code{allot}ed memory is no longer on the
 2326: top of the dictionary ``stack'').
 2327: 
 2328: Alternatively, you can use @code{allocate} and @code{free} which allow
 2329: freeing memory in any order:
 2330: 
 2331: @example
 2332: 10 cells allocate throw .s
 2333: 20 cells allocate throw .s
 2334: swap
 2335: free throw
 2336: free throw
 2337: @end example
 2338: 
 2339: The @code{throw}s deal with errors (e.g., out of memory).
 2340: 
 2341: And there is also a
 2342: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2343: garbage collector}, which eliminates the need to @code{free} memory
 2344: explicitly.
 2345: 
 2346: Reference: @ref{Memory}.
 2347: 
 2348: 
 2349: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2350: @section Characters and Strings
 2351: @cindex strings tutorial
 2352: @cindex characters tutorial
 2353: 
 2354: On the stack characters take up a cell, like numbers.  In memory they
 2355: have their own size (one 8-bit byte on most systems), and therefore
 2356: require their own words for memory access:
 2357: 
 2358: @example
 2359: create v4 
 2360:   104 c, 97 c, 108 c, 108 c, 111 c,
 2361: v4 4 chars + c@@ .
 2362: v4 5 chars dump
 2363: @end example
 2364: 
 2365: The preferred representation of strings on the stack is @code{addr
 2366: u-count}, where @code{addr} is the address of the first character and
 2367: @code{u-count} is the number of characters in the string.
 2368: 
 2369: @example
 2370: v4 5 type
 2371: @end example
 2372: 
 2373: You get a string constant with
 2374: 
 2375: @example
 2376: s" hello, world" .s
 2377: type
 2378: @end example
 2379: 
 2380: Make sure you have a space between @code{s"} and the string; @code{s"}
 2381: is a normal Forth word and must be delimited with white space (try what
 2382: happens when you remove the space).
 2383: 
 2384: However, this interpretive use of @code{s"} is quite restricted: the
 2385: string exists only until the next call of @code{s"} (some Forth systems
 2386: keep more than one of these strings, but usually they still have a
 2387: limited lifetime).
 2388: 
 2389: @example
 2390: s" hello," s" world" .s
 2391: type
 2392: type
 2393: @end example
 2394: 
 2395: You can also use @code{s"} in a definition, and the resulting
 2396: strings then live forever (well, for as long as the definition):
 2397: 
 2398: @example
 2399: : foo s" hello," s" world" ;
 2400: foo .s
 2401: type
 2402: type
 2403: @end example
 2404: 
 2405: @assignment
 2406: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2407: Implement @code{type ( addr u -- )}.
 2408: @endassignment
 2409: 
 2410: Reference: @ref{Memory Blocks}.
 2411: 
 2412: 
 2413: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
 2414: @section Alignment
 2415: @cindex alignment tutorial
 2416: @cindex memory alignment tutorial
 2417: 
 2418: On many processors cells have to be aligned in memory, if you want to
 2419: access them with @code{@@} and @code{!} (and even if the processor does
 2420: not require alignment, access to aligned cells is faster).
 2421: 
 2422: @code{Create} aligns @code{here} (i.e., the place where the next
 2423: allocation will occur, and that the @code{create}d word points to).
 2424: Likewise, the memory produced by @code{allocate} starts at an aligned
 2425: address.  Adding a number of @code{cells} to an aligned address produces
 2426: another aligned address.
 2427: 
 2428: However, address arithmetic involving @code{char+} and @code{chars} can
 2429: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2430: a-addr )} produces the next aligned address:
 2431: 
 2432: @example
 2433: v3 char+ aligned .s @@ .
 2434: v3 char+ .s @@ .
 2435: @end example
 2436: 
 2437: Similarly, @code{align} advances @code{here} to the next aligned
 2438: address:
 2439: 
 2440: @example
 2441: create v5 97 c,
 2442: here .
 2443: align here .
 2444: 1000 ,
 2445: @end example
 2446: 
 2447: Note that you should use aligned addresses even if your processor does
 2448: not require them, if you want your program to be portable.
 2449: 
 2450: Reference: @ref{Address arithmetic}.
 2451: 
 2452: 
 2453: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
 2454: @section Files
 2455: @cindex files tutorial
 2456: 
 2457: This section gives a short introduction into how to use files inside
 2458: Forth. It's broken up into five easy steps:
 2459: 
 2460: @enumerate 1
 2461: @item Opened an ASCII text file for input
 2462: @item Opened a file for output
 2463: @item Read input file until string matched (or some other condition matched)
 2464: @item Wrote some lines from input ( modified or not) to output
 2465: @item Closed the files.
 2466: @end enumerate
 2467: 
 2468: @subsection Open file for input
 2469: 
 2470: @example
 2471: s" foo.in"  r/o open-file throw Value fd-in
 2472: @end example
 2473: 
 2474: @subsection Create file for output
 2475: 
 2476: @example
 2477: s" foo.out" w/o create-file throw Value fd-out
 2478: @end example
 2479: 
 2480: The available file modes are r/o for read-only access, r/w for
 2481: read-write access, and w/o for write-only access. You could open both
 2482: files with r/w, too, if you like. All file words return error codes; for
 2483: most applications, it's best to pass there error codes with @code{throw}
 2484: to the outer error handler.
 2485: 
 2486: If you want words for opening and assigning, define them as follows:
 2487: 
 2488: @example
 2489: 0 Value fd-in
 2490: 0 Value fd-out
 2491: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2492: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2493: @end example
 2494: 
 2495: Usage example:
 2496: 
 2497: @example
 2498: s" foo.in" open-input
 2499: s" foo.out" open-output
 2500: @end example
 2501: 
 2502: @subsection Scan file for a particular line
 2503: 
 2504: @example
 2505: 256 Constant max-line
 2506: Create line-buffer  max-line 2 + allot
 2507: 
 2508: : scan-file ( addr u -- )
 2509:   begin
 2510:       line-buffer max-line fd-in read-line throw
 2511:   while
 2512:          >r 2dup line-buffer r> compare 0=
 2513:      until
 2514:   else
 2515:      drop
 2516:   then
 2517:   2drop ;
 2518: @end example
 2519: 
 2520: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2521: the buffer at addr, and returns the number of bytes read, a flag that is
 2522: false when the end of file is reached, and an error code.
 2523: 
 2524: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2525: returns zero if both strings are equal. It returns a positive number if
 2526: the first string is lexically greater, a negative if the second string
 2527: is lexically greater.
 2528: 
 2529: We haven't seen this loop here; it has two exits. Since the @code{while}
 2530: exits with the number of bytes read on the stack, we have to clean up
 2531: that separately; that's after the @code{else}.
 2532: 
 2533: Usage example:
 2534: 
 2535: @example
 2536: s" The text I search is here" scan-file
 2537: @end example
 2538: 
 2539: @subsection Copy input to output
 2540: 
 2541: @example
 2542: : copy-file ( -- )
 2543:   begin
 2544:       line-buffer max-line fd-in read-line throw
 2545:   while
 2546:       line-buffer swap fd-out write-file throw
 2547:   repeat ;
 2548: @end example
 2549: 
 2550: @subsection Close files
 2551: 
 2552: @example
 2553: fd-in close-file throw
 2554: fd-out close-file throw
 2555: @end example
 2556: 
 2557: Likewise, you can put that into definitions, too:
 2558: 
 2559: @example
 2560: : close-input ( -- )  fd-in close-file throw ;
 2561: : close-output ( -- )  fd-out close-file throw ;
 2562: @end example
 2563: 
 2564: @assignment
 2565: How could you modify @code{copy-file} so that it copies until a second line is
 2566: matched? Can you write a program that extracts a section of a text file,
 2567: given the line that starts and the line that terminates that section?
 2568: @endassignment
 2569: 
 2570: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2571: @section Interpretation and Compilation Semantics and Immediacy
 2572: @cindex semantics tutorial
 2573: @cindex interpretation semantics tutorial
 2574: @cindex compilation semantics tutorial
 2575: @cindex immediate, tutorial
 2576: 
 2577: When a word is compiled, it behaves differently from being interpreted.
 2578: E.g., consider @code{+}:
 2579: 
 2580: @example
 2581: 1 2 + .
 2582: : foo + ;
 2583: @end example
 2584: 
 2585: These two behaviours are known as compilation and interpretation
 2586: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2587: is to append the interpretation semantics to the currently defined word
 2588: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2589: later, the interpretation semantics of @code{+} (i.e., adding two
 2590: numbers) will be performed.
 2591: 
 2592: However, there are words with non-default compilation semantics, e.g.,
 2593: the control-flow words like @code{if}.  You can use @code{immediate} to
 2594: change the compilation semantics of the last defined word to be equal to
 2595: the interpretation semantics:
 2596: 
 2597: @example
 2598: : [FOO] ( -- )
 2599:  5 . ; immediate
 2600: 
 2601: [FOO]
 2602: : bar ( -- )
 2603:   [FOO] ;
 2604: bar
 2605: see bar
 2606: @end example
 2607: 
 2608: Two conventions to mark words with non-default compilation semnatics are
 2609: names with brackets (more frequently used) and to write them all in
 2610: upper case (less frequently used).
 2611: 
 2612: In Gforth (and many other systems) you can also remove the
 2613: interpretation semantics with @code{compile-only} (the compilation
 2614: semantics is derived from the original interpretation semantics):
 2615: 
 2616: @example
 2617: : flip ( -- )
 2618:  6 . ; compile-only \ but not immediate
 2619: flip
 2620: 
 2621: : flop ( -- )
 2622:  flip ;
 2623: flop
 2624: @end example
 2625: 
 2626: In this example the interpretation semantics of @code{flop} is equal to
 2627: the original interpretation semantics of @code{flip}.
 2628: 
 2629: The text interpreter has two states: in interpret state, it performs the
 2630: interpretation semantics of words it encounters; in compile state, it
 2631: performs the compilation semantics of these words.
 2632: 
 2633: Among other things, @code{:} switches into compile state, and @code{;}
 2634: switches back to interpret state.  They contain the factors @code{]}
 2635: (switch to compile state) and @code{[} (switch to interpret state), that
 2636: do nothing but switch the state.
 2637: 
 2638: @example
 2639: : xxx ( -- )
 2640:   [ 5 . ]
 2641: ;
 2642: 
 2643: xxx
 2644: see xxx
 2645: @end example
 2646: 
 2647: These brackets are also the source of the naming convention mentioned
 2648: above.
 2649: 
 2650: Reference: @ref{Interpretation and Compilation Semantics}.
 2651: 
 2652: 
 2653: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2654: @section Execution Tokens
 2655: @cindex execution tokens tutorial
 2656: @cindex XT tutorial
 2657: 
 2658: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2659: cell representing the interpretation semantics of a word.  You can
 2660: execute this semantics with @code{execute}:
 2661: 
 2662: @example
 2663: ' + .s
 2664: 1 2 rot execute .
 2665: @end example
 2666: 
 2667: The XT is similar to a function pointer in C.  However, parameter
 2668: passing through the stack makes it a little more flexible:
 2669: 
 2670: @example
 2671: : map-array ( ... addr u xt -- ... )
 2672: \ executes xt ( ... x -- ... ) for every element of the array starting
 2673: \ at addr and containing u elements
 2674:   @{ xt @}
 2675:   cells over + swap ?do
 2676:     i @@ xt execute
 2677:   1 cells +loop ;
 2678: 
 2679: create a 3 , 4 , 2 , -1 , 4 ,
 2680: a 5 ' . map-array .s
 2681: 0 a 5 ' + map-array .
 2682: s" max-n" environment? drop .s
 2683: a 5 ' min map-array .
 2684: @end example
 2685: 
 2686: You can use map-array with the XTs of words that consume one element
 2687: more than they produce.  In theory you can also use it with other XTs,
 2688: but the stack effect then depends on the size of the array, which is
 2689: hard to understand.
 2690: 
 2691: Since XTs are cell-sized, you can store them in memory and manipulate
 2692: them on the stack like other cells.  You can also compile the XT into a
 2693: word with @code{compile,}:
 2694: 
 2695: @example
 2696: : foo1 ( n1 n2 -- n )
 2697:    [ ' + compile, ] ;
 2698: see foo
 2699: @end example
 2700: 
 2701: This is non-standard, because @code{compile,} has no compilation
 2702: semantics in the standard, but it works in good Forth systems.  For the
 2703: broken ones, use
 2704: 
 2705: @example
 2706: : [compile,] compile, ; immediate
 2707: 
 2708: : foo1 ( n1 n2 -- n )
 2709:    [ ' + ] [compile,] ;
 2710: see foo
 2711: @end example
 2712: 
 2713: @code{'} is a word with default compilation semantics; it parses the
 2714: next word when its interpretation semantics are executed, not during
 2715: compilation:
 2716: 
 2717: @example
 2718: : foo ( -- xt )
 2719:   ' ;
 2720: see foo
 2721: : bar ( ... "word" -- ... )
 2722:   ' execute ;
 2723: see bar
 2724: 1 2 bar + .
 2725: @end example
 2726: 
 2727: You often want to parse a word during compilation and compile its XT so
 2728: it will be pushed on the stack at run-time.  @code{[']} does this:
 2729: 
 2730: @example
 2731: : xt-+ ( -- xt )
 2732:   ['] + ;
 2733: see xt-+
 2734: 1 2 xt-+ execute .
 2735: @end example
 2736: 
 2737: Many programmers tend to see @code{'} and the word it parses as one
 2738: unit, and expect it to behave like @code{[']} when compiled, and are
 2739: confused by the actual behaviour.  If you are, just remember that the
 2740: Forth system just takes @code{'} as one unit and has no idea that it is
 2741: a parsing word (attempts to convenience programmers in this issue have
 2742: usually resulted in even worse pitfalls, see
 2743: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2744: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2745: 
 2746: Note that the state of the interpreter does not come into play when
 2747: creating and executing XTs.  I.e., even when you execute @code{'} in
 2748: compile state, it still gives you the interpretation semantics.  And
 2749: whatever that state is, @code{execute} performs the semantics
 2750: represented by the XT (i.e., for XTs produced with @code{'} the
 2751: interpretation semantics).
 2752: 
 2753: Reference: @ref{Tokens for Words}.
 2754: 
 2755: 
 2756: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2757: @section Exceptions
 2758: @cindex exceptions tutorial
 2759: 
 2760: @code{throw ( n -- )} causes an exception unless n is zero.
 2761: 
 2762: @example
 2763: 100 throw .s
 2764: 0 throw .s
 2765: @end example
 2766: 
 2767: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2768: it catches exceptions and pushes the number of the exception on the
 2769: stack (or 0, if the xt executed without exception).  If there was an
 2770: exception, the stacks have the same depth as when entering @code{catch}:
 2771: 
 2772: @example
 2773: .s
 2774: 3 0 ' / catch .s
 2775: 3 2 ' / catch .s
 2776: @end example
 2777: 
 2778: @assignment
 2779: Try the same with @code{execute} instead of @code{catch}.
 2780: @endassignment
 2781: 
 2782: @code{Throw} always jumps to the dynamically next enclosing
 2783: @code{catch}, even if it has to leave several call levels to achieve
 2784: this:
 2785: 
 2786: @example
 2787: : foo 100 throw ;
 2788: : foo1 foo ." after foo" ;
 2789: : bar ['] foo1 catch ;
 2790: bar .
 2791: @end example
 2792: 
 2793: It is often important to restore a value upon leaving a definition, even
 2794: if the definition is left through an exception.  You can ensure this
 2795: like this:
 2796: 
 2797: @example
 2798: : ...
 2799:    save-x
 2800:    ['] word-changing-x catch ( ... n )
 2801:    restore-x
 2802:    ( ... n ) throw ;
 2803: @end example
 2804: 
 2805: Gforth provides an alternative syntax in addition to @code{catch}:
 2806: @code{try ... recover ... endtry}.  If the code between @code{try} and
 2807: @code{recover} has an exception, the stack depths are restored, the
 2808: exception number is pushed on the stack, and the code between
 2809: @code{recover} and @code{endtry} is performed.  E.g., the definition for
 2810: @code{catch} is
 2811: 
 2812: @example
 2813: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
 2814:   try
 2815:     execute 0
 2816:   recover
 2817:     nip
 2818:   endtry ;
 2819: @end example
 2820: 
 2821: The equivalent to the restoration code above is
 2822: 
 2823: @example
 2824: : ...
 2825:   save-x
 2826:   try
 2827:     word-changing-x 0
 2828:   recover endtry
 2829:   restore-x
 2830:   throw ;
 2831: @end example
 2832: 
 2833: This works if @code{word-changing-x} does not change the stack depth,
 2834: otherwise you should add some code between @code{recover} and
 2835: @code{endtry} to balance the stack.
 2836: 
 2837: Reference: @ref{Exception Handling}.
 2838: 
 2839: 
 2840: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 2841: @section Defining Words
 2842: @cindex defining words tutorial
 2843: @cindex does> tutorial
 2844: @cindex create...does> tutorial
 2845: 
 2846: @c before semantics?
 2847: 
 2848: @code{:}, @code{create}, and @code{variable} are definition words: They
 2849: define other words.  @code{Constant} is another definition word:
 2850: 
 2851: @example
 2852: 5 constant foo
 2853: foo .
 2854: @end example
 2855: 
 2856: You can also use the prefixes @code{2} (double-cell) and @code{f}
 2857: (floating point) with @code{variable} and @code{constant}.
 2858: 
 2859: You can also define your own defining words.  E.g.:
 2860: 
 2861: @example
 2862: : variable ( "name" -- )
 2863:   create 0 , ;
 2864: @end example
 2865: 
 2866: You can also define defining words that create words that do something
 2867: other than just producing their address:
 2868: 
 2869: @example
 2870: : constant ( n "name" -- )
 2871:   create ,
 2872: does> ( -- n )
 2873:   ( addr ) @@ ;
 2874: 
 2875: 5 constant foo
 2876: foo .
 2877: @end example
 2878: 
 2879: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 2880: @code{does>} replaces @code{;}, but it also does something else: It
 2881: changes the last defined word such that it pushes the address of the
 2882: body of the word and then performs the code after the @code{does>}
 2883: whenever it is called.
 2884: 
 2885: In the example above, @code{constant} uses @code{,} to store 5 into the
 2886: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 2887: the body onto the stack, then (in the code after the @code{does>})
 2888: fetches the 5 from there.
 2889: 
 2890: The stack comment near the @code{does>} reflects the stack effect of the
 2891: defined word, not the stack effect of the code after the @code{does>}
 2892: (the difference is that the code expects the address of the body that
 2893: the stack comment does not show).
 2894: 
 2895: You can use these definition words to do factoring in cases that involve
 2896: (other) definition words.  E.g., a field offset is always added to an
 2897: address.  Instead of defining
 2898: 
 2899: @example
 2900: 2 cells constant offset-field1
 2901: @end example
 2902: 
 2903: and using this like
 2904: 
 2905: @example
 2906: ( addr ) offset-field1 +
 2907: @end example
 2908: 
 2909: you can define a definition word
 2910: 
 2911: @example
 2912: : simple-field ( n "name" -- )
 2913:   create ,
 2914: does> ( n1 -- n1+n )
 2915:   ( addr ) @@ + ;
 2916: @end example
 2917: 
 2918: Definition and use of field offsets now look like this:
 2919: 
 2920: @example
 2921: 2 cells simple-field field1
 2922: create mystruct 4 cells allot
 2923: mystruct .s field1 .s drop
 2924: @end example
 2925: 
 2926: If you want to do something with the word without performing the code
 2927: after the @code{does>}, you can access the body of a @code{create}d word
 2928: with @code{>body ( xt -- addr )}:
 2929: 
 2930: @example
 2931: : value ( n "name" -- )
 2932:   create ,
 2933: does> ( -- n1 )
 2934:   @@ ;
 2935: : to ( n "name" -- )
 2936:   ' >body ! ;
 2937: 
 2938: 5 value foo
 2939: foo .
 2940: 7 to foo
 2941: foo .
 2942: @end example
 2943: 
 2944: @assignment
 2945: Define @code{defer ( "name" -- )}, which creates a word that stores an
 2946: XT (at the start the XT of @code{abort}), and upon execution
 2947: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 2948: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 2949: recursion is one application of @code{defer}.
 2950: @endassignment
 2951: 
 2952: Reference: @ref{User-defined Defining Words}.
 2953: 
 2954: 
 2955: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 2956: @section Arrays and Records
 2957: @cindex arrays tutorial
 2958: @cindex records tutorial
 2959: @cindex structs tutorial
 2960: 
 2961: Forth has no standard words for defining data structures such as arrays
 2962: and records (structs in C terminology), but you can build them yourself
 2963: based on address arithmetic.  You can also define words for defining
 2964: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 2965: 
 2966: One of the first projects a Forth newcomer sets out upon when learning
 2967: about defining words is an array defining word (possibly for
 2968: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 2969: learn something from it.  However, don't be disappointed when you later
 2970: learn that you have little use for these words (inappropriate use would
 2971: be even worse).  I have not yet found a set of useful array words yet;
 2972: the needs are just too diverse, and named, global arrays (the result of
 2973: naive use of defining words) are often not flexible enough (e.g.,
 2974: consider how to pass them as parameters).  Another such project is a set
 2975: of words to help dealing with strings.
 2976: 
 2977: On the other hand, there is a useful set of record words, and it has
 2978: been defined in @file{compat/struct.fs}; these words are predefined in
 2979: Gforth.  They are explained in depth elsewhere in this manual (see
 2980: @pxref{Structures}).  The @code{simple-field} example above is
 2981: simplified variant of fields in this package.
 2982: 
 2983: 
 2984: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 2985: @section @code{POSTPONE}
 2986: @cindex postpone tutorial
 2987: 
 2988: You can compile the compilation semantics (instead of compiling the
 2989: interpretation semantics) of a word with @code{POSTPONE}:
 2990: 
 2991: @example
 2992: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 2993:  POSTPONE + ; immediate
 2994: : foo ( n1 n2 -- n )
 2995:  MY-+ ;
 2996: 1 2 foo .
 2997: see foo
 2998: @end example
 2999: 
 3000: During the definition of @code{foo} the text interpreter performs the
 3001: compilation semantics of @code{MY-+}, which performs the compilation
 3002: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3003: 
 3004: This example also displays separate stack comments for the compilation
 3005: semantics and for the stack effect of the compiled code.  For words with
 3006: default compilation semantics these stack effects are usually not
 3007: displayed; the stack effect of the compilation semantics is always
 3008: @code{( -- )} for these words, the stack effect for the compiled code is
 3009: the stack effect of the interpretation semantics.
 3010: 
 3011: Note that the state of the interpreter does not come into play when
 3012: performing the compilation semantics in this way.  You can also perform
 3013: it interpretively, e.g.:
 3014: 
 3015: @example
 3016: : foo2 ( n1 n2 -- n )
 3017:  [ MY-+ ] ;
 3018: 1 2 foo .
 3019: see foo
 3020: @end example
 3021: 
 3022: However, there are some broken Forth systems where this does not always
 3023: work, and therefore this practice was been declared non-standard in
 3024: 1999.
 3025: @c !! repair.fs
 3026: 
 3027: Here is another example for using @code{POSTPONE}:
 3028: 
 3029: @example
 3030: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3031:  POSTPONE negate POSTPONE + ; immediate compile-only
 3032: : bar ( n1 n2 -- n )
 3033:   MY-- ;
 3034: 2 1 bar .
 3035: see bar
 3036: @end example
 3037: 
 3038: You can define @code{ENDIF} in this way:
 3039: 
 3040: @example
 3041: : ENDIF ( Compilation: orig -- )
 3042:   POSTPONE then ; immediate
 3043: @end example
 3044: 
 3045: @assignment
 3046: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3047: @code{2dup}, but compiles @code{over over}.
 3048: @endassignment
 3049: 
 3050: @c !! @xref{Macros} for reference
 3051: 
 3052: 
 3053: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3054: @section @code{Literal}
 3055: @cindex literal tutorial
 3056: 
 3057: You cannot @code{POSTPONE} numbers:
 3058: 
 3059: @example
 3060: : [FOO] POSTPONE 500 ; immediate
 3061: @end example
 3062: 
 3063: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3064: 
 3065: @example
 3066: : [FOO] ( compilation: --; run-time: -- n )
 3067:   500 POSTPONE literal ; immediate
 3068: 
 3069: : flip [FOO] ;
 3070: flip .
 3071: see flip
 3072: @end example
 3073: 
 3074: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3075: semantics are executed) and pushes it at run-time (when the code it
 3076: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3077: number computed at compile time into the current word:
 3078: 
 3079: @example
 3080: : bar ( -- n )
 3081:   [ 2 2 + ] literal ;
 3082: see bar
 3083: @end example
 3084: 
 3085: @assignment
 3086: Write @code{]L} which allows writing the example above as @code{: bar (
 3087: -- n ) [ 2 2 + ]L ;}
 3088: @endassignment
 3089: 
 3090: @c !! @xref{Macros} for reference
 3091: 
 3092: 
 3093: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3094: @section Advanced macros
 3095: @cindex macros, advanced tutorial
 3096: @cindex run-time code generation, tutorial
 3097: 
 3098: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3099: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3100: expensive operation in some Forth implementations.  You can use
 3101: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3102: and produce a word that contains the word to be performed directly:
 3103: 
 3104: @c use ]] ... [[
 3105: @example
 3106: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3107: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3108: \ array beginning at addr and containing u elements
 3109:   @{ xt @}
 3110:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3111:     POSTPONE i POSTPONE @@ xt compile,
 3112:   1 cells POSTPONE literal POSTPONE +loop ;
 3113: 
 3114: : sum-array ( addr u -- n )
 3115:  0 rot rot [ ' + compile-map-array ] ;
 3116: see sum-array
 3117: a 5 sum-array .
 3118: @end example
 3119: 
 3120: You can use the full power of Forth for generating the code; here's an
 3121: example where the code is generated in a loop:
 3122: 
 3123: @example
 3124: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3125: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3126:   POSTPONE tuck POSTPONE @@
 3127:   POSTPONE literal POSTPONE * POSTPONE +
 3128:   POSTPONE swap POSTPONE cell+ ;
 3129: 
 3130: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3131: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3132:   0 postpone literal postpone swap
 3133:   [ ' compile-vmul-step compile-map-array ]
 3134:   postpone drop ;
 3135: see compile-vmul
 3136: 
 3137: : a-vmul ( addr -- n )
 3138: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3139:  [ a 5 compile-vmul ] ;
 3140: see a-vmul
 3141: a a-vmul .
 3142: @end example
 3143: 
 3144: This example uses @code{compile-map-array} to show off, but you could
 3145: also use @code{map-array} instead (try it now!).
 3146: 
 3147: You can use this technique for efficient multiplication of large
 3148: matrices.  In matrix multiplication, you multiply every line of one
 3149: matrix with every column of the other matrix.  You can generate the code
 3150: for one line once, and use it for every column.  The only downside of
 3151: this technique is that it is cumbersome to recover the memory consumed
 3152: by the generated code when you are done (and in more complicated cases
 3153: it is not possible portably).
 3154: 
 3155: @c !! @xref{Macros} for reference
 3156: 
 3157: 
 3158: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3159: @section Compilation Tokens
 3160: @cindex compilation tokens, tutorial
 3161: @cindex CT, tutorial
 3162: 
 3163: This section is Gforth-specific.  You can skip it.
 3164: 
 3165: @code{' word compile,} compiles the interpretation semantics.  For words
 3166: with default compilation semantics this is the same as performing the
 3167: compilation semantics.  To represent the compilation semantics of other
 3168: words (e.g., words like @code{if} that have no interpretation
 3169: semantics), Gforth has the concept of a compilation token (CT,
 3170: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3171: You can perform the compilation semantics represented by a CT with
 3172: @code{execute}:
 3173: 
 3174: @example
 3175: : foo2 ( n1 n2 -- n )
 3176:    [ comp' + execute ] ;
 3177: see foo
 3178: @end example
 3179: 
 3180: You can compile the compilation semantics represented by a CT with
 3181: @code{postpone,}:
 3182: 
 3183: @example
 3184: : foo3 ( -- )
 3185:   [ comp' + postpone, ] ;
 3186: see foo3
 3187: @end example
 3188: 
 3189: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3190: @code{comp'} is particularly useful for words that have no
 3191: interpretation semantics:
 3192: 
 3193: @example
 3194: ' if
 3195: comp' if .s 2drop
 3196: @end example
 3197: 
 3198: Reference: @ref{Tokens for Words}.
 3199: 
 3200: 
 3201: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3202: @section Wordlists and Search Order
 3203: @cindex wordlists tutorial
 3204: @cindex search order, tutorial
 3205: 
 3206: The dictionary is not just a memory area that allows you to allocate
 3207: memory with @code{allot}, it also contains the Forth words, arranged in
 3208: several wordlists.  When searching for a word in a wordlist,
 3209: conceptually you start searching at the youngest and proceed towards
 3210: older words (in reality most systems nowadays use hash-tables); i.e., if
 3211: you define a word with the same name as an older word, the new word
 3212: shadows the older word.
 3213: 
 3214: Which wordlists are searched in which order is determined by the search
 3215: order.  You can display the search order with @code{order}.  It displays
 3216: first the search order, starting with the wordlist searched first, then
 3217: it displays the wordlist that will contain newly defined words.
 3218: 
 3219: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3220: 
 3221: @example
 3222: wordlist constant mywords
 3223: @end example
 3224: 
 3225: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3226: defined words (the @emph{current} wordlist):
 3227: 
 3228: @example
 3229: mywords set-current
 3230: order
 3231: @end example
 3232: 
 3233: Gforth does not display a name for the wordlist in @code{mywords}
 3234: because this wordlist was created anonymously with @code{wordlist}.
 3235: 
 3236: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3237: you want to put something into a specific wordlist without overall
 3238: effect on the current wordlist, this typically looks like this:
 3239: 
 3240: @example
 3241: get-current mywords set-current ( wid )
 3242: create someword
 3243: ( wid ) set-current
 3244: @end example
 3245: 
 3246: You can write the search order with @code{set-order ( wid1 .. widn n --
 3247: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3248: searched wordlist is topmost.
 3249: 
 3250: @example
 3251: get-order mywords swap 1+ set-order
 3252: order
 3253: @end example
 3254: 
 3255: Yes, the order of wordlists in the output of @code{order} is reversed
 3256: from stack comments and the output of @code{.s} and thus unintuitive.
 3257: 
 3258: @assignment
 3259: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3260: wordlist to the search order.  Define @code{previous ( -- )}, which
 3261: removes the first searched wordlist from the search order.  Experiment
 3262: with boundary conditions (you will see some crashes or situations that
 3263: are hard or impossible to leave).
 3264: @endassignment
 3265: 
 3266: The search order is a powerful foundation for providing features similar
 3267: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3268: programs in this way has disadvantages for debugging and reuse/factoring
 3269: that overcome the advantages in my experience (I don't do huge projects,
 3270: though).  These disadvantages are not so clear in other
 3271: languages/programming environments, because these languages are not so
 3272: strong in debugging and reuse.
 3273: 
 3274: @c !! example
 3275: 
 3276: Reference: @ref{Word Lists}.
 3277: 
 3278: @c ******************************************************************
 3279: @node Introduction, Words, Tutorial, Top
 3280: @comment node-name,     next,           previous, up
 3281: @chapter An Introduction to ANS Forth
 3282: @cindex Forth - an introduction
 3283: 
 3284: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3285: that it is slower-paced in its examples, but uses them to dive deep into
 3286: explaining Forth internals (not covered by the Tutorial).  Apart from
 3287: that, this chapter covers far less material.  It is suitable for reading
 3288: without using a computer.
 3289: 
 3290: The primary purpose of this manual is to document Gforth. However, since
 3291: Forth is not a widely-known language and there is a lack of up-to-date
 3292: teaching material, it seems worthwhile to provide some introductory
 3293: material.  For other sources of Forth-related
 3294: information, see @ref{Forth-related information}.
 3295: 
 3296: The examples in this section should work on any ANS Forth; the
 3297: output shown was produced using Gforth. Each example attempts to
 3298: reproduce the exact output that Gforth produces. If you try out the
 3299: examples (and you should), what you should type is shown @kbd{like this}
 3300: and Gforth's response is shown @code{like this}. The single exception is
 3301: that, where the example shows @key{RET} it means that you should
 3302: press the ``carriage return'' key. Unfortunately, some output formats for
 3303: this manual cannot show the difference between @kbd{this} and
 3304: @code{this} which will make trying out the examples harder (but not
 3305: impossible).
 3306: 
 3307: Forth is an unusual language. It provides an interactive development
 3308: environment which includes both an interpreter and compiler. Forth
 3309: programming style encourages you to break a problem down into many
 3310: @cindex factoring
 3311: small fragments (@dfn{factoring}), and then to develop and test each
 3312: fragment interactively. Forth advocates assert that breaking the
 3313: edit-compile-test cycle used by conventional programming languages can
 3314: lead to great productivity improvements.
 3315: 
 3316: @menu
 3317: * Introducing the Text Interpreter::  
 3318: * Stacks and Postfix notation::  
 3319: * Your first definition::       
 3320: * How does that work?::         
 3321: * Forth is written in Forth::   
 3322: * Review - elements of a Forth system::  
 3323: * Where to go next::            
 3324: * Exercises::                   
 3325: @end menu
 3326: 
 3327: @comment ----------------------------------------------
 3328: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3329: @section Introducing the Text Interpreter
 3330: @cindex text interpreter
 3331: @cindex outer interpreter
 3332: 
 3333: @c IMO this is too detailed and the pace is too slow for
 3334: @c an introduction.  If you know German, take a look at
 3335: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3336: @c to see how I do it - anton 
 3337: 
 3338: @c nac-> Where I have accepted your comments 100% and modified the text
 3339: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3340: @c response like this to attempt to rationalise what I have done. Of
 3341: @c course, this is a very clumsy mechanism for something that would be
 3342: @c done far more efficiently over a beer. Please delete any dialogue
 3343: @c you consider closed.
 3344: 
 3345: When you invoke the Forth image, you will see a startup banner printed
 3346: and nothing else (if you have Gforth installed on your system, try
 3347: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3348: its command line interpreter, which is called the @dfn{Text Interpreter}
 3349: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3350: about the text interpreter as you read through this chapter, for more
 3351: detail @pxref{The Text Interpreter}).
 3352: 
 3353: Although it's not obvious, Forth is actually waiting for your
 3354: input. Type a number and press the @key{RET} key:
 3355: 
 3356: @example
 3357: @kbd{45@key{RET}}  ok
 3358: @end example
 3359: 
 3360: Rather than give you a prompt to invite you to input something, the text
 3361: interpreter prints a status message @i{after} it has processed a line
 3362: of input. The status message in this case (``@code{ ok}'' followed by
 3363: carriage-return) indicates that the text interpreter was able to process
 3364: all of your input successfully. Now type something illegal:
 3365: 
 3366: @example
 3367: @kbd{qwer341@key{RET}}
 3368: :1: Undefined word
 3369: qwer341
 3370: ^^^^^^^
 3371: $400D2BA8 Bounce
 3372: $400DBDA8 no.extensions
 3373: @end example
 3374: 
 3375: The exact text, other than the ``Undefined word'' may differ slightly on
 3376: your system, but the effect is the same; when the text interpreter
 3377: detects an error, it discards any remaining text on a line, resets
 3378: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
 3379: messages}.
 3380: 
 3381: The text interpreter waits for you to press carriage-return, and then
 3382: processes your input line. Starting at the beginning of the line, it
 3383: breaks the line into groups of characters separated by spaces. For each
 3384: group of characters in turn, it makes two attempts to do something:
 3385: 
 3386: @itemize @bullet
 3387: @item
 3388: @cindex name dictionary
 3389: It tries to treat it as a command. It does this by searching a @dfn{name
 3390: dictionary}. If the group of characters matches an entry in the name
 3391: dictionary, the name dictionary provides the text interpreter with
 3392: information that allows the text interpreter perform some actions. In
 3393: Forth jargon, we say that the group
 3394: @cindex word
 3395: @cindex definition
 3396: @cindex execution token
 3397: @cindex xt
 3398: of characters names a @dfn{word}, that the dictionary search returns an
 3399: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3400: word, and that the text interpreter executes the xt. Often, the terms
 3401: @dfn{word} and @dfn{definition} are used interchangeably.
 3402: @item
 3403: If the text interpreter fails to find a match in the name dictionary, it
 3404: tries to treat the group of characters as a number in the current number
 3405: base (when you start up Forth, the current number base is base 10). If
 3406: the group of characters legitimately represents a number, the text
 3407: interpreter pushes the number onto a stack (we'll learn more about that
 3408: in the next section).
 3409: @end itemize
 3410: 
 3411: If the text interpreter is unable to do either of these things with any
 3412: group of characters, it discards the group of characters and the rest of
 3413: the line, then prints an error message. If the text interpreter reaches
 3414: the end of the line without error, it prints the status message ``@code{ ok}''
 3415: followed by carriage-return.
 3416: 
 3417: This is the simplest command we can give to the text interpreter:
 3418: 
 3419: @example
 3420: @key{RET}  ok
 3421: @end example
 3422: 
 3423: The text interpreter did everything we asked it to do (nothing) without
 3424: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3425: command:
 3426: 
 3427: @example
 3428: @kbd{12 dup fred dup@key{RET}}
 3429: :1: Undefined word
 3430: 12 dup fred dup
 3431:        ^^^^
 3432: $400D2BA8 Bounce
 3433: $400DBDA8 no.extensions
 3434: @end example
 3435: 
 3436: When you press the carriage-return key, the text interpreter starts to
 3437: work its way along the line:
 3438: 
 3439: @itemize @bullet
 3440: @item
 3441: When it gets to the space after the @code{2}, it takes the group of
 3442: characters @code{12} and looks them up in the name
 3443: dictionary@footnote{We can't tell if it found them or not, but assume
 3444: for now that it did not}. There is no match for this group of characters
 3445: in the name dictionary, so it tries to treat them as a number. It is
 3446: able to do this successfully, so it puts the number, 12, ``on the stack''
 3447: (whatever that means).
 3448: @item
 3449: The text interpreter resumes scanning the line and gets the next group
 3450: of characters, @code{dup}. It looks it up in the name dictionary and
 3451: (you'll have to take my word for this) finds it, and executes the word
 3452: @code{dup} (whatever that means).
 3453: @item
 3454: Once again, the text interpreter resumes scanning the line and gets the
 3455: group of characters @code{fred}. It looks them up in the name
 3456: dictionary, but can't find them. It tries to treat them as a number, but
 3457: they don't represent any legal number.
 3458: @end itemize
 3459: 
 3460: At this point, the text interpreter gives up and prints an error
 3461: message. The error message shows exactly how far the text interpreter
 3462: got in processing the line. In particular, it shows that the text
 3463: interpreter made no attempt to do anything with the final character
 3464: group, @code{dup}, even though we have good reason to believe that the
 3465: text interpreter would have no problem looking that word up and
 3466: executing it a second time.
 3467: 
 3468: 
 3469: @comment ----------------------------------------------
 3470: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3471: @section Stacks, postfix notation and parameter passing
 3472: @cindex text interpreter
 3473: @cindex outer interpreter
 3474: 
 3475: In procedural programming languages (like C and Pascal), the
 3476: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3477: functions or procedures are called with @dfn{explicit parameters}. For
 3478: example, in C we might write:
 3479: 
 3480: @example
 3481: total = total + new_volume(length,height,depth);
 3482: @end example
 3483: 
 3484: @noindent
 3485: where new_volume is a function-call to another piece of code, and total,
 3486: length, height and depth are all variables. length, height and depth are
 3487: parameters to the function-call.
 3488: 
 3489: In Forth, the equivalent of the function or procedure is the
 3490: @dfn{definition} and parameters are implicitly passed between
 3491: definitions using a shared stack that is visible to the
 3492: programmer. Although Forth does support variables, the existence of the
 3493: stack means that they are used far less often than in most other
 3494: programming languages. When the text interpreter encounters a number, it
 3495: will place (@dfn{push}) it on the stack. There are several stacks (the
 3496: actual number is implementation-dependent ...) and the particular stack
 3497: used for any operation is implied unambiguously by the operation being
 3498: performed. The stack used for all integer operations is called the @dfn{data
 3499: stack} and, since this is the stack used most commonly, references to
 3500: ``the data stack'' are often abbreviated to ``the stack''.
 3501: 
 3502: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3503: 
 3504: @example
 3505: @kbd{1 2 3@key{RET}}  ok
 3506: @end example
 3507: 
 3508: Then this instructs the text interpreter to placed three numbers on the
 3509: (data) stack. An analogy for the behaviour of the stack is to take a
 3510: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3511: the table. The 3 was the last card onto the pile (``last-in'') and if
 3512: you take a card off the pile then, unless you're prepared to fiddle a
 3513: bit, the card that you take off will be the 3 (``first-out''). The
 3514: number that will be first-out of the stack is called the @dfn{top of
 3515: stack}, which
 3516: @cindex TOS definition
 3517: is often abbreviated to @dfn{TOS}.
 3518: 
 3519: To understand how parameters are passed in Forth, consider the
 3520: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3521: be surprised to learn that this definition performs addition. More
 3522: precisely, it adds two number together and produces a result. Where does
 3523: it get the two numbers from? It takes the top two numbers off the
 3524: stack. Where does it place the result? On the stack. You can act-out the
 3525: behaviour of @code{+} with your playing cards like this:
 3526: 
 3527: @itemize @bullet
 3528: @item
 3529: Pick up two cards from the stack on the table
 3530: @item
 3531: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3532: numbers''
 3533: @item
 3534: Decide that the answer is 5
 3535: @item
 3536: Shuffle the two cards back into the pack and find a 5
 3537: @item
 3538: Put a 5 on the remaining ace that's on the table.
 3539: @end itemize
 3540: 
 3541: If you don't have a pack of cards handy but you do have Forth running,
 3542: you can use the definition @code{.s} to show the current state of the stack,
 3543: without affecting the stack. Type:
 3544: 
 3545: @example
 3546: @kbd{clearstack 1 2 3@key{RET}} ok
 3547: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3548: @end example
 3549: 
 3550: The text interpreter looks up the word @code{clearstack} and executes
 3551: it; it tidies up the stack and removes any entries that may have been
 3552: left on it by earlier examples. The text interpreter pushes each of the
 3553: three numbers in turn onto the stack. Finally, the text interpreter
 3554: looks up the word @code{.s} and executes it. The effect of executing
 3555: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3556: followed by a list of all the items on the stack; the item on the far
 3557: right-hand side is the TOS.
 3558: 
 3559: You can now type:
 3560: 
 3561: @example
 3562: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3563: @end example
 3564: 
 3565: @noindent
 3566: which is correct; there are now 2 items on the stack and the result of
 3567: the addition is 5.
 3568: 
 3569: If you're playing with cards, try doing a second addition: pick up the
 3570: two cards, work out that their sum is 6, shuffle them into the pack,
 3571: look for a 6 and place that on the table. You now have just one item on
 3572: the stack. What happens if you try to do a third addition? Pick up the
 3573: first card, pick up the second card -- ah! There is no second card. This
 3574: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3575: do the same thing with Forth it often reports an error (probably a Stack
 3576: Underflow or an Invalid Memory Address error).
 3577: 
 3578: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3579: which simply accepts that there is a finite amount of storage space
 3580: reserved for the stack. To stretch the playing card analogy, if you had
 3581: enough packs of cards and you piled the cards up on the table, you would
 3582: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3583: allows you to set the maximum size of the stacks. In general, the only
 3584: time that you will get a stack overflow is because a definition has a
 3585: bug in it and is generating data on the stack uncontrollably.
 3586: 
 3587: There's one final use for the playing card analogy. If you model your
 3588: stack using a pack of playing cards, the maximum number of items on
 3589: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3590: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3591: possible numbers are positive integer numbers 1 through 13; you can't
 3592: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3593: think about some of the cards, you can accommodate different
 3594: numbers. For example, you could think of the Jack as representing 0,
 3595: the Queen as representing -1 and the King as representing -2. Your
 3596: @i{range} remains unchanged (you can still only represent a total of 13
 3597: numbers) but the numbers that you can represent are -2 through 10.
 3598: 
 3599: In that analogy, the limit was the amount of information that a single
 3600: stack entry could hold, and Forth has a similar limit. In Forth, the
 3601: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3602: implementation dependent and affects the maximum value that a stack
 3603: entry can hold. A Standard Forth provides a cell size of at least
 3604: 16-bits, and most desktop systems use a cell size of 32-bits.
 3605: 
 3606: Forth does not do any type checking for you, so you are free to
 3607: manipulate and combine stack items in any way you wish. A convenient way
 3608: of treating stack items is as 2's complement signed integers, and that
 3609: is what Standard words like @code{+} do. Therefore you can type:
 3610: 
 3611: @example
 3612: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3613: @end example
 3614: 
 3615: If you use numbers and definitions like @code{+} in order to turn Forth
 3616: into a great big pocket calculator, you will realise that it's rather
 3617: different from a normal calculator. Rather than typing 2 + 3 = you had
 3618: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3619: result). The terminology used to describe this difference is to say that
 3620: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3621: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3622: operators are separate), also called @dfn{Reverse Polish Notation}.
 3623: 
 3624: Whilst postfix notation might look confusing to begin with, it has
 3625: several important advantages:
 3626: 
 3627: @itemize @bullet
 3628: @item
 3629: it is unambiguous
 3630: @item
 3631: it is more concise
 3632: @item
 3633: it fits naturally with a stack-based system
 3634: @end itemize
 3635: 
 3636: To examine these claims in more detail, consider these sums:
 3637: 
 3638: @example
 3639: 6 + 5 * 4 =
 3640: 4 * 5 + 6 =
 3641: @end example
 3642: 
 3643: If you're just learning maths or your maths is very rusty, you will
 3644: probably come up with the answer 44 for the first and 26 for the
 3645: second. If you are a bit of a whizz at maths you will remember the
 3646: @i{convention} that multiplication takes precendence over addition, and
 3647: you'd come up with the answer 26 both times. To explain the answer 26
 3648: to someone who got the answer 44, you'd probably rewrite the first sum
 3649: like this:
 3650: 
 3651: @example
 3652: 6 + (5 * 4) =
 3653: @end example
 3654: 
 3655: If what you really wanted was to perform the addition before the
 3656: multiplication, you would have to use parentheses to force it.
 3657: 
 3658: If you did the first two sums on a pocket calculator you would probably
 3659: get the right answers, unless you were very cautious and entered them using
 3660: these keystroke sequences:
 3661: 
 3662: 6 + 5 = * 4 =
 3663: 4 * 5 = + 6 =
 3664: 
 3665: Postfix notation is unambiguous because the order that the operators
 3666: are applied is always explicit; that also means that parentheses are
 3667: never required. The operators are @i{active} (the act of quoting the
 3668: operator makes the operation occur) which removes the need for ``=''.
 3669: 
 3670: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3671: equivalent ways:
 3672: 
 3673: @example
 3674: 6 5 4 * +      or:
 3675: 5 4 * 6 +
 3676: @end example
 3677: 
 3678: An important thing that you should notice about this notation is that
 3679: the @i{order} of the numbers does not change; if you want to subtract
 3680: 2 from 10 you type @code{10 2 -}.
 3681: 
 3682: The reason that Forth uses postfix notation is very simple to explain: it
 3683: makes the implementation extremely simple, and it follows naturally from
 3684: using the stack as a mechanism for passing parameters. Another way of
 3685: thinking about this is to realise that all Forth definitions are
 3686: @i{active}; they execute as they are encountered by the text
 3687: interpreter. The result of this is that the syntax of Forth is trivially
 3688: simple.
 3689: 
 3690: 
 3691: 
 3692: @comment ----------------------------------------------
 3693: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3694: @section Your first Forth definition
 3695: @cindex first definition
 3696: 
 3697: Until now, the examples we've seen have been trivial; we've just been
 3698: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3699: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3700: again@footnote{That's not quite true. If you press the up-arrow key on
 3701: your keyboard you should be able to scroll back to any earlier command,
 3702: edit it and re-enter it.} In this section we'll see how to add new
 3703: words to Forth's vocabulary.
 3704: 
 3705: The easiest way to create a new word is to use a @dfn{colon
 3706: definition}. We'll define a few and try them out before worrying too
 3707: much about how they work. Try typing in these examples; be careful to
 3708: copy the spaces accurately:
 3709: 
 3710: @example
 3711: : add-two 2 + . ;
 3712: : greet ." Hello and welcome" ;
 3713: : demo 5 add-two ;
 3714: @end example
 3715: 
 3716: @noindent
 3717: Now try them out:
 3718: 
 3719: @example
 3720: @kbd{greet@key{RET}} Hello and welcome  ok
 3721: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3722: @kbd{4 add-two@key{RET}} 6  ok
 3723: @kbd{demo@key{RET}} 7  ok
 3724: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3725: @end example
 3726: 
 3727: The first new thing that we've introduced here is the pair of words
 3728: @code{:} and @code{;}. These are used to start and terminate a new
 3729: definition, respectively. The first word after the @code{:} is the name
 3730: for the new definition.
 3731: 
 3732: As you can see from the examples, a definition is built up of words that
 3733: have already been defined; Forth makes no distinction between
 3734: definitions that existed when you started the system up, and those that
 3735: you define yourself.
 3736: 
 3737: The examples also introduce the words @code{.} (dot), @code{."}
 3738: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3739: the stack and displays it. It's like @code{.s} except that it only
 3740: displays the top item of the stack and it is destructive; after it has
 3741: executed, the number is no longer on the stack. There is always one
 3742: space printed after the number, and no spaces before it. Dot-quote
 3743: defines a string (a sequence of characters) that will be printed when
 3744: the word is executed. The string can contain any printable characters
 3745: except @code{"}. A @code{"} has a special function; it is not a Forth
 3746: word but it acts as a delimiter (the way that delimiters work is
 3747: described in the next section). Finally, @code{dup} duplicates the value
 3748: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3749: 
 3750: We already know that the text interpreter searches through the
 3751: dictionary to locate names. If you've followed the examples earlier, you
 3752: will already have a definition called @code{add-two}. Lets try modifying
 3753: it by typing in a new definition:
 3754: 
 3755: @example
 3756: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3757: @end example
 3758: 
 3759: Forth recognised that we were defining a word that already exists, and
 3760: printed a message to warn us of that fact. Let's try out the new
 3761: definition:
 3762: 
 3763: @example
 3764: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3765: @end example
 3766: 
 3767: @noindent
 3768: All that we've actually done here, though, is to create a new
 3769: definition, with a particular name. The fact that there was already a
 3770: definition with the same name did not make any difference to the way
 3771: that the new definition was created (except that Forth printed a warning
 3772: message). The old definition of add-two still exists (try @code{demo}
 3773: again to see that this is true). Any new definition will use the new
 3774: definition of @code{add-two}, but old definitions continue to use the
 3775: version that already existed at the time that they were @code{compiled}.
 3776: 
 3777: Before you go on to the next section, try defining and redefining some
 3778: words of your own.
 3779: 
 3780: @comment ----------------------------------------------
 3781: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3782: @section How does that work?
 3783: @cindex parsing words
 3784: 
 3785: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3786: 
 3787: @c Is it a good idea to talk about the interpretation semantics of a
 3788: @c number? We don't have an xt to go along with it. - anton
 3789: 
 3790: @c Now that I have eliminated execution semantics, I wonder if it would not
 3791: @c be better to keep them (or add run-time semantics), to make it easier to
 3792: @c explain what compilation semantics usually does. - anton
 3793: 
 3794: @c nac-> I removed the term ``default compilation sematics'' from the
 3795: @c introductory chapter. Removing ``execution semantics'' was making
 3796: @c everything simpler to explain, then I think the use of this term made
 3797: @c everything more complex again. I replaced it with ``default
 3798: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3799: @c ``a definition that has neither the immediate nor the compile-only
 3800: @c flag set''.
 3801: 
 3802: @c anton: I have eliminated default semantics (except in one place where it
 3803: @c means "default interpretation and compilation semantics"), because it
 3804: @c makes no sense in the presence of combined words.  I reverted to
 3805: @c "execution semantics" where necessary.
 3806: 
 3807: @c nac-> I reworded big chunks of the ``how does that work''
 3808: @c section (and, unusually for me, I think I even made it shorter!).  See
 3809: @c what you think -- I know I have not addressed your primary concern
 3810: @c that it is too heavy-going for an introduction. From what I understood
 3811: @c of your course notes it looks as though they might be a good framework. 
 3812: @c Things that I've tried to capture here are some things that came as a
 3813: @c great revelation here when I first understood them. Also, I like the
 3814: @c fact that a very simple code example shows up almost all of the issues
 3815: @c that you need to understand to see how Forth works. That's unique and
 3816: @c worthwhile to emphasise.
 3817: 
 3818: @c anton: I think it's a good idea to present the details, especially those
 3819: @c that you found to be a revelation, and probably the tutorial tries to be
 3820: @c too superficial and does not get some of the things across that make
 3821: @c Forth special.  I do believe that most of the time these things should
 3822: @c be discussed at the end of a section or in separate sections instead of
 3823: @c in the middle of a section (e.g., the stuff you added in "User-defined
 3824: @c defining words" leads in a completely different direction from the rest
 3825: @c of the section).
 3826: 
 3827: Now we're going to take another look at the definition of @code{add-two}
 3828: from the previous section. From our knowledge of the way that the text
 3829: interpreter works, we would have expected this result when we tried to
 3830: define @code{add-two}:
 3831: 
 3832: @example
 3833: @kbd{: add-two 2 + . ;@key{RET}}
 3834:   ^^^^^^^
 3835: Error: Undefined word
 3836: @end example
 3837: 
 3838: The reason that this didn't happen is bound up in the way that @code{:}
 3839: works. The word @code{:} does two special things. The first special
 3840: thing that it does prevents the text interpreter from ever seeing the
 3841: characters @code{add-two}. The text interpreter uses a variable called
 3842: @cindex modifying >IN
 3843: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 3844: input line. When it encounters the word @code{:} it behaves in exactly
 3845: the same way as it does for any other word; it looks it up in the name
 3846: dictionary, finds its xt and executes it. When @code{:} executes, it
 3847: looks at the input buffer, finds the word @code{add-two} and advances the
 3848: value of @code{>IN} to point past it. It then does some other stuff
 3849: associated with creating the new definition (including creating an entry
 3850: for @code{add-two} in the name dictionary). When the execution of @code{:}
 3851: completes, control returns to the text interpreter, which is oblivious
 3852: to the fact that it has been tricked into ignoring part of the input
 3853: line.
 3854: 
 3855: @cindex parsing words
 3856: Words like @code{:} -- words that advance the value of @code{>IN} and so
 3857: prevent the text interpreter from acting on the whole of the input line
 3858: -- are called @dfn{parsing words}.
 3859: 
 3860: @cindex @code{state} - effect on the text interpreter
 3861: @cindex text interpreter - effect of state
 3862: The second special thing that @code{:} does is change the value of a
 3863: variable called @code{state}, which affects the way that the text
 3864: interpreter behaves. When Gforth starts up, @code{state} has the value
 3865: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 3866: colon definition (started with @code{:}), @code{state} is set to -1 and
 3867: the text interpreter is said to be @dfn{compiling}.
 3868: 
 3869: In this example, the text interpreter is compiling when it processes the
 3870: string ``@code{2 + . ;}''. It still breaks the string down into
 3871: character sequences in the same way. However, instead of pushing the
 3872: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 3873: into the definition of @code{add-two} that will make the number @code{2} get
 3874: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 3875: the behaviours of @code{+} and @code{.} are also compiled into the
 3876: definition.
 3877: 
 3878: One category of words don't get compiled. These so-called @dfn{immediate
 3879: words} get executed (performed @i{now}) regardless of whether the text
 3880: interpreter is interpreting or compiling. The word @code{;} is an
 3881: immediate word. Rather than being compiled into the definition, it
 3882: executes. Its effect is to terminate the current definition, which
 3883: includes changing the value of @code{state} back to 0.
 3884: 
 3885: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 3886: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 3887: definition.
 3888: 
 3889: In Forth, every word or number can be described in terms of two
 3890: properties:
 3891: 
 3892: @itemize @bullet
 3893: @item
 3894: @cindex interpretation semantics
 3895: Its @dfn{interpretation semantics} describe how it will behave when the
 3896: text interpreter encounters it in @dfn{interpret} state. The
 3897: interpretation semantics of a word are represented by an @dfn{execution
 3898: token}.
 3899: @item
 3900: @cindex compilation semantics
 3901: Its @dfn{compilation semantics} describe how it will behave when the
 3902: text interpreter encounters it in @dfn{compile} state. The compilation
 3903: semantics of a word are represented in an implementation-dependent way;
 3904: Gforth uses a @dfn{compilation token}.
 3905: @end itemize
 3906: 
 3907: @noindent
 3908: Numbers are always treated in a fixed way:
 3909: 
 3910: @itemize @bullet
 3911: @item
 3912: When the number is @dfn{interpreted}, its behaviour is to push the
 3913: number onto the stack.
 3914: @item
 3915: When the number is @dfn{compiled}, a piece of code is appended to the
 3916: current definition that pushes the number when it runs. (In other words,
 3917: the compilation semantics of a number are to postpone its interpretation
 3918: semantics until the run-time of the definition that it is being compiled
 3919: into.)
 3920: @end itemize
 3921: 
 3922: Words don't behave in such a regular way, but most have @i{default
 3923: semantics} which means that they behave like this:
 3924: 
 3925: @itemize @bullet
 3926: @item
 3927: The @dfn{interpretation semantics} of the word are to do something useful.
 3928: @item
 3929: The @dfn{compilation semantics} of the word are to append its
 3930: @dfn{interpretation semantics} to the current definition (so that its
 3931: run-time behaviour is to do something useful).
 3932: @end itemize
 3933: 
 3934: @cindex immediate words
 3935: The actual behaviour of any particular word can be controlled by using
 3936: the words @code{immediate} and @code{compile-only} when the word is
 3937: defined. These words set flags in the name dictionary entry of the most
 3938: recently defined word, and these flags are retrieved by the text
 3939: interpreter when it finds the word in the name dictionary.
 3940: 
 3941: A word that is marked as @dfn{immediate} has compilation semantics that
 3942: are identical to its interpretation semantics. In other words, it
 3943: behaves like this:
 3944: 
 3945: @itemize @bullet
 3946: @item
 3947: The @dfn{interpretation semantics} of the word are to do something useful.
 3948: @item
 3949: The @dfn{compilation semantics} of the word are to do something useful
 3950: (and actually the same thing); i.e., it is executed during compilation.
 3951: @end itemize
 3952: 
 3953: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 3954: performing the interpretation semantics of the word directly; an attempt
 3955: to do so will generate an error. It is never necessary to use
 3956: @code{compile-only} (and it is not even part of ANS Forth, though it is
 3957: provided by many implementations) but it is good etiquette to apply it
 3958: to a word that will not behave correctly (and might have unexpected
 3959: side-effects) in interpret state. For example, it is only legal to use
 3960: the conditional word @code{IF} within a definition. If you forget this
 3961: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 3962: @code{compile-only} allows the text interpreter to generate a helpful
 3963: error message rather than subjecting you to the consequences of your
 3964: folly.
 3965: 
 3966: This example shows the difference between an immediate and a
 3967: non-immediate word:
 3968: 
 3969: @example
 3970: : show-state state @@ . ;
 3971: : show-state-now show-state ; immediate
 3972: : word1 show-state ;
 3973: : word2 show-state-now ;
 3974: @end example
 3975: 
 3976: The word @code{immediate} after the definition of @code{show-state-now}
 3977: makes that word an immediate word. These definitions introduce a new
 3978: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 3979: variable, and leaves it on the stack. Therefore, the behaviour of
 3980: @code{show-state} is to print a number that represents the current value
 3981: of @code{state}.
 3982: 
 3983: When you execute @code{word1}, it prints the number 0, indicating that
 3984: the system is interpreting. When the text interpreter compiled the
 3985: definition of @code{word1}, it encountered @code{show-state} whose
 3986: compilation semantics are to append its interpretation semantics to the
 3987: current definition. When you execute @code{word1}, it performs the
 3988: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 3989: (and therefore @code{show-state}) are executed, the system is
 3990: interpreting.
 3991: 
 3992: When you pressed @key{RET} after entering the definition of @code{word2},
 3993: you should have seen the number -1 printed, followed by ``@code{
 3994: ok}''. When the text interpreter compiled the definition of
 3995: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 3996: whose compilation semantics are therefore to perform its interpretation
 3997: semantics. It is executed straight away (even before the text
 3998: interpreter has moved on to process another group of characters; the
 3999: @code{;} in this example). The effect of executing it are to display the
 4000: value of @code{state} @i{at the time that the definition of}
 4001: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4002: system is compiling at this time. If you execute @code{word2} it does
 4003: nothing at all.
 4004: 
 4005: @cindex @code{."}, how it works
 4006: Before leaving the subject of immediate words, consider the behaviour of
 4007: @code{."} in the definition of @code{greet}, in the previous
 4008: section. This word is both a parsing word and an immediate word. Notice
 4009: that there is a space between @code{."} and the start of the text
 4010: @code{Hello and welcome}, but that there is no space between the last
 4011: letter of @code{welcome} and the @code{"} character. The reason for this
 4012: is that @code{."} is a Forth word; it must have a space after it so that
 4013: the text interpreter can identify it. The @code{"} is not a Forth word;
 4014: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4015: is displayed, there is neither a space before the @code{H} nor after the
 4016: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4017: that @code{greet} is defined. When it executes, its behaviour is to
 4018: search forward in the input line looking for the delimiter. When it
 4019: finds the delimiter, it updates @code{>IN} to point past the
 4020: delimiter. It also compiles some magic code into the definition of
 4021: @code{greet}; the xt of a run-time routine that prints a text string. It
 4022: compiles the string @code{Hello and welcome} into memory so that it is
 4023: available to be printed later. When the text interpreter gains control,
 4024: the next word it finds in the input stream is @code{;} and so it
 4025: terminates the definition of @code{greet}.
 4026: 
 4027: 
 4028: @comment ----------------------------------------------
 4029: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4030: @section Forth is written in Forth
 4031: @cindex structure of Forth programs
 4032: 
 4033: When you start up a Forth compiler, a large number of definitions
 4034: already exist. In Forth, you develop a new application using bottom-up
 4035: programming techniques to create new definitions that are defined in
 4036: terms of existing definitions. As you create each definition you can
 4037: test and debug it interactively.
 4038: 
 4039: If you have tried out the examples in this section, you will probably
 4040: have typed them in by hand; when you leave Gforth, your definitions will
 4041: be lost. You can avoid this by using a text editor to enter Forth source
 4042: code into a file, and then loading code from the file using
 4043: @code{include} (@pxref{Forth source files}). A Forth source file is
 4044: processed by the text interpreter, just as though you had typed it in by
 4045: hand@footnote{Actually, there are some subtle differences -- see
 4046: @ref{The Text Interpreter}.}.
 4047: 
 4048: Gforth also supports the traditional Forth alternative to using text
 4049: files for program entry (@pxref{Blocks}).
 4050: 
 4051: In common with many, if not most, Forth compilers, most of Gforth is
 4052: actually written in Forth. All of the @file{.fs} files in the
 4053: installation directory@footnote{For example,
 4054: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4055: study to see examples of Forth programming.
 4056: 
 4057: Gforth maintains a history file that records every line that you type to
 4058: the text interpreter. This file is preserved between sessions, and is
 4059: used to provide a command-line recall facility. If you enter long
 4060: definitions by hand, you can use a text editor to paste them out of the
 4061: history file into a Forth source file for reuse at a later time
 4062: (for more information @pxref{Command-line editing}).
 4063: 
 4064: 
 4065: @comment ----------------------------------------------
 4066: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4067: @section Review - elements of a Forth system
 4068: @cindex elements of a Forth system
 4069: 
 4070: To summarise this chapter:
 4071: 
 4072: @itemize @bullet
 4073: @item
 4074: Forth programs use @dfn{factoring} to break a problem down into small
 4075: fragments called @dfn{words} or @dfn{definitions}.
 4076: @item
 4077: Forth program development is an interactive process.
 4078: @item
 4079: The main command loop that accepts input, and controls both
 4080: interpretation and compilation, is called the @dfn{text interpreter}
 4081: (also known as the @dfn{outer interpreter}).
 4082: @item
 4083: Forth has a very simple syntax, consisting of words and numbers
 4084: separated by spaces or carriage-return characters. Any additional syntax
 4085: is imposed by @dfn{parsing words}.
 4086: @item
 4087: Forth uses a stack to pass parameters between words. As a result, it
 4088: uses postfix notation.
 4089: @item
 4090: To use a word that has previously been defined, the text interpreter
 4091: searches for the word in the @dfn{name dictionary}.
 4092: @item
 4093: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4094: @item
 4095: The text interpreter uses the value of @code{state} to select between
 4096: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4097: semantics} of a word that it encounters.
 4098: @item
 4099: The relationship between the @dfn{interpretation semantics} and
 4100: @dfn{compilation semantics} for a word
 4101: depend upon the way in which the word was defined (for example, whether
 4102: it is an @dfn{immediate} word).
 4103: @item
 4104: Forth definitions can be implemented in Forth (called @dfn{high-level
 4105: definitions}) or in some other way (usually a lower-level language and
 4106: as a result often called @dfn{low-level definitions}, @dfn{code
 4107: definitions} or @dfn{primitives}).
 4108: @item
 4109: Many Forth systems are implemented mainly in Forth.
 4110: @end itemize
 4111: 
 4112: 
 4113: @comment ----------------------------------------------
 4114: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4115: @section Where To Go Next
 4116: @cindex where to go next
 4117: 
 4118: Amazing as it may seem, if you have read (and understood) this far, you
 4119: know almost all the fundamentals about the inner workings of a Forth
 4120: system. You certainly know enough to be able to read and understand the
 4121: rest of this manual and the ANS Forth document, to learn more about the
 4122: facilities that Forth in general and Gforth in particular provide. Even
 4123: scarier, you know almost enough to implement your own Forth system.
 4124: However, that's not a good idea just yet... better to try writing some
 4125: programs in Gforth.
 4126: 
 4127: Forth has such a rich vocabulary that it can be hard to know where to
 4128: start in learning it. This section suggests a few sets of words that are
 4129: enough to write small but useful programs. Use the word index in this
 4130: document to learn more about each word, then try it out and try to write
 4131: small definitions using it. Start by experimenting with these words:
 4132: 
 4133: @itemize @bullet
 4134: @item
 4135: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4136: @item
 4137: Comparison: @code{MIN MAX =}
 4138: @item
 4139: Logic: @code{AND OR XOR NOT}
 4140: @item
 4141: Stack manipulation: @code{DUP DROP SWAP OVER}
 4142: @item
 4143: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4144: @item
 4145: Input/Output: @code{. ." EMIT CR KEY}
 4146: @item
 4147: Defining words: @code{: ; CREATE}
 4148: @item
 4149: Memory allocation words: @code{ALLOT ,}
 4150: @item
 4151: Tools: @code{SEE WORDS .S MARKER}
 4152: @end itemize
 4153: 
 4154: When you have mastered those, go on to:
 4155: 
 4156: @itemize @bullet
 4157: @item
 4158: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4159: @item
 4160: Memory access: @code{@@ !}
 4161: @end itemize
 4162: 
 4163: When you have mastered these, there's nothing for it but to read through
 4164: the whole of this manual and find out what you've missed.
 4165: 
 4166: @comment ----------------------------------------------
 4167: @node Exercises,  , Where to go next, Introduction
 4168: @section Exercises
 4169: @cindex exercises
 4170: 
 4171: TODO: provide a set of programming excercises linked into the stuff done
 4172: already and into other sections of the manual. Provide solutions to all
 4173: the exercises in a .fs file in the distribution.
 4174: 
 4175: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4176: 
 4177: @c excercises:
 4178: @c 1. take inches and convert to feet and inches.
 4179: @c 2. take temperature and convert from fahrenheight to celcius;
 4180: @c    may need to care about symmetric vs floored??
 4181: @c 3. take input line and do character substitution
 4182: @c    to encipher or decipher
 4183: @c 4. as above but work on a file for in and out
 4184: @c 5. take input line and convert to pig-latin 
 4185: @c
 4186: @c thing of sets of things to exercise then come up with
 4187: @c problems that need those things.
 4188: 
 4189: 
 4190: @c ******************************************************************
 4191: @node Words, Error messages, Introduction, Top
 4192: @chapter Forth Words
 4193: @cindex words
 4194: 
 4195: @menu
 4196: * Notation::                    
 4197: * Case insensitivity::          
 4198: * Comments::                    
 4199: * Boolean Flags::               
 4200: * Arithmetic::                  
 4201: * Stack Manipulation::          
 4202: * Memory::                      
 4203: * Control Structures::          
 4204: * Defining Words::              
 4205: * Interpretation and Compilation Semantics::  
 4206: * Tokens for Words::            
 4207: * Compiling words::             
 4208: * The Text Interpreter::        
 4209: * The Input Stream::            
 4210: * Word Lists::                  
 4211: * Environmental Queries::       
 4212: * Files::                       
 4213: * Blocks::                      
 4214: * Other I/O::                   
 4215: * Locals::                      
 4216: * Structures::                  
 4217: * Object-oriented Forth::       
 4218: * Programming Tools::           
 4219: * Assembler and Code Words::    
 4220: * Threading Words::             
 4221: * Passing Commands to the OS::  
 4222: * Keeping track of Time::       
 4223: * Miscellaneous Words::         
 4224: @end menu
 4225: 
 4226: @node Notation, Case insensitivity, Words, Words
 4227: @section Notation
 4228: @cindex notation of glossary entries
 4229: @cindex format of glossary entries
 4230: @cindex glossary notation format
 4231: @cindex word glossary entry format
 4232: 
 4233: The Forth words are described in this section in the glossary notation
 4234: that has become a de-facto standard for Forth texts:
 4235: 
 4236: @format
 4237: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4238: @end format
 4239: @i{Description}
 4240: 
 4241: @table @var
 4242: @item word
 4243: The name of the word.
 4244: 
 4245: @item Stack effect
 4246: @cindex stack effect
 4247: The stack effect is written in the notation @code{@i{before} --
 4248: @i{after}}, where @i{before} and @i{after} describe the top of
 4249: stack entries before and after the execution of the word. The rest of
 4250: the stack is not touched by the word. The top of stack is rightmost,
 4251: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4252: uses a separate floating point stack, but a unified stack
 4253: notation. Also, return stack effects are not shown in @i{stack
 4254: effect}, but in @i{Description}. The name of a stack item describes
 4255: the type and/or the function of the item. See below for a discussion of
 4256: the types.
 4257: 
 4258: All words have two stack effects: A compile-time stack effect and a
 4259: run-time stack effect. The compile-time stack-effect of most words is
 4260: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4261: this standard behaviour, or the word does other unusual things at
 4262: compile time, both stack effects are shown; otherwise only the run-time
 4263: stack effect is shown.
 4264: 
 4265: @cindex pronounciation of words
 4266: @item pronunciation
 4267: How the word is pronounced.
 4268: 
 4269: @cindex wordset
 4270: @cindex environment wordset
 4271: @item wordset
 4272: The ANS Forth standard is divided into several word sets. A standard
 4273: system need not support all of them. Therefore, in theory, the fewer
 4274: word sets your program uses the more portable it will be. However, we
 4275: suspect that most ANS Forth systems on personal machines will feature
 4276: all word sets. Words that are not defined in ANS Forth have
 4277: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4278: describes words that will work in future releases of Gforth;
 4279: @code{gforth-internal} words are more volatile. Environmental query
 4280: strings are also displayed like words; you can recognize them by the
 4281: @code{environment} in the word set field.
 4282: 
 4283: @item Description
 4284: A description of the behaviour of the word.
 4285: @end table
 4286: 
 4287: @cindex types of stack items
 4288: @cindex stack item types
 4289: The type of a stack item is specified by the character(s) the name
 4290: starts with:
 4291: 
 4292: @table @code
 4293: @item f
 4294: @cindex @code{f}, stack item type
 4295: Boolean flags, i.e. @code{false} or @code{true}.
 4296: @item c
 4297: @cindex @code{c}, stack item type
 4298: Char
 4299: @item w
 4300: @cindex @code{w}, stack item type
 4301: Cell, can contain an integer or an address
 4302: @item n
 4303: @cindex @code{n}, stack item type
 4304: signed integer
 4305: @item u
 4306: @cindex @code{u}, stack item type
 4307: unsigned integer
 4308: @item d
 4309: @cindex @code{d}, stack item type
 4310: double sized signed integer
 4311: @item ud
 4312: @cindex @code{ud}, stack item type
 4313: double sized unsigned integer
 4314: @item r
 4315: @cindex @code{r}, stack item type
 4316: Float (on the FP stack)
 4317: @item a-
 4318: @cindex @code{a_}, stack item type
 4319: Cell-aligned address
 4320: @item c-
 4321: @cindex @code{c_}, stack item type
 4322: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4323: @item f-
 4324: @cindex @code{f_}, stack item type
 4325: Float-aligned address
 4326: @item df-
 4327: @cindex @code{df_}, stack item type
 4328: Address aligned for IEEE double precision float
 4329: @item sf-
 4330: @cindex @code{sf_}, stack item type
 4331: Address aligned for IEEE single precision float
 4332: @item xt
 4333: @cindex @code{xt}, stack item type
 4334: Execution token, same size as Cell
 4335: @item wid
 4336: @cindex @code{wid}, stack item type
 4337: Word list ID, same size as Cell
 4338: @item ior, wior
 4339: @cindex ior type description
 4340: @cindex wior type description
 4341: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4342: @item f83name
 4343: @cindex @code{f83name}, stack item type
 4344: Pointer to a name structure
 4345: @item "
 4346: @cindex @code{"}, stack item type
 4347: string in the input stream (not on the stack). The terminating character
 4348: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4349: quotes.
 4350: @end table
 4351: 
 4352: @comment ----------------------------------------------
 4353: @node Case insensitivity, Comments, Notation, Words
 4354: @section Case insensitivity
 4355: @cindex case sensitivity
 4356: @cindex upper and lower case
 4357: 
 4358: Gforth is case-insensitive; you can enter definitions and invoke
 4359: Standard words using upper, lower or mixed case (however,
 4360: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4361: options}).
 4362: 
 4363: ANS Forth only @i{requires} implementations to recognise Standard words
 4364: when they are typed entirely in upper case. Therefore, a Standard
 4365: program must use upper case for all Standard words. You can use whatever
 4366: case you like for words that you define, but in a Standard program you
 4367: have to use the words in the same case that you defined them.
 4368: 
 4369: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4370: wordlists, @pxref{Word Lists}).
 4371: 
 4372: Two people have asked how to convert Gforth to be case-sensitive; while
 4373: we think this is a bad idea, you can change all wordlists into tables
 4374: like this:
 4375: 
 4376: @example
 4377: ' table-find forth-wordlist wordlist-map @ !
 4378: @end example
 4379: 
 4380: Note that you now have to type the predefined words in the same case
 4381: that we defined them, which are varying.  You may want to convert them
 4382: to your favourite case before doing this operation (I won't explain how,
 4383: because if you are even contemplating doing this, you'd better have
 4384: enough knowledge of Forth systems to know this already).
 4385: 
 4386: @node Comments, Boolean Flags, Case insensitivity, Words
 4387: @section Comments
 4388: @cindex comments
 4389: 
 4390: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4391: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4392: 
 4393: 
 4394: doc-(
 4395: doc-\
 4396: doc-\G
 4397: 
 4398: 
 4399: @node Boolean Flags, Arithmetic, Comments, Words
 4400: @section Boolean Flags
 4401: @cindex Boolean flags
 4402: 
 4403: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4404: flag @code{false} and a flag with all bits set represents the flag
 4405: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4406: a cell that has @i{any} bit set as @code{true}.
 4407: @c on and off to Memory? 
 4408: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4409: 
 4410: doc-true
 4411: doc-false
 4412: doc-on
 4413: doc-off
 4414: 
 4415: 
 4416: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4417: @section Arithmetic
 4418: @cindex arithmetic words
 4419: 
 4420: @cindex division with potentially negative operands
 4421: Forth arithmetic is not checked, i.e., you will not hear about integer
 4422: overflow on addition or multiplication, you may hear about division by
 4423: zero if you are lucky. The operator is written after the operands, but
 4424: the operands are still in the original order. I.e., the infix @code{2-1}
 4425: corresponds to @code{2 1 -}. Forth offers a variety of division
 4426: operators. If you perform division with potentially negative operands,
 4427: you do not want to use @code{/} or @code{/mod} with its undefined
 4428: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4429: former, @pxref{Mixed precision}).
 4430: @comment TODO discuss the different division forms and the std approach
 4431: 
 4432: @menu
 4433: * Single precision::            
 4434: * Double precision::            Double-cell integer arithmetic
 4435: * Bitwise operations::          
 4436: * Numeric comparison::          
 4437: * Mixed precision::             Operations with single and double-cell integers
 4438: * Floating Point::              
 4439: @end menu
 4440: 
 4441: @node Single precision, Double precision, Arithmetic, Arithmetic
 4442: @subsection Single precision
 4443: @cindex single precision arithmetic words
 4444: 
 4445: @c !! cell undefined
 4446: 
 4447: By default, numbers in Forth are single-precision integers that are one
 4448: cell in size. They can be signed or unsigned, depending upon how you
 4449: treat them. For the rules used by the text interpreter for recognising
 4450: single-precision integers see @ref{Number Conversion}.
 4451: 
 4452: These words are all defined for signed operands, but some of them also
 4453: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4454: @code{*}.
 4455: 
 4456: doc-+
 4457: doc-1+
 4458: doc--
 4459: doc-1-
 4460: doc-*
 4461: doc-/
 4462: doc-mod
 4463: doc-/mod
 4464: doc-negate
 4465: doc-abs
 4466: doc-min
 4467: doc-max
 4468: doc-floored
 4469: 
 4470: 
 4471: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4472: @subsection Double precision
 4473: @cindex double precision arithmetic words
 4474: 
 4475: For the rules used by the text interpreter for
 4476: recognising double-precision integers, see @ref{Number Conversion}.
 4477: 
 4478: A double precision number is represented by a cell pair, with the most
 4479: significant cell at the TOS. It is trivial to convert an unsigned single
 4480: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4481: represented by Gforth using 2's complement arithmetic, converting a
 4482: signed single to a (signed) double requires sign-extension across the
 4483: most significant cell. This can be achieved using @code{s>d}. The moral
 4484: of the story is that you cannot convert a number without knowing whether
 4485: it represents an unsigned or a signed number.
 4486: 
 4487: These words are all defined for signed operands, but some of them also
 4488: work for unsigned numbers: @code{d+}, @code{d-}.
 4489: 
 4490: doc-s>d
 4491: doc-d>s
 4492: doc-d+
 4493: doc-d-
 4494: doc-dnegate
 4495: doc-dabs
 4496: doc-dmin
 4497: doc-dmax
 4498: 
 4499: 
 4500: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4501: @subsection Bitwise operations
 4502: @cindex bitwise operation words
 4503: 
 4504: 
 4505: doc-and
 4506: doc-or
 4507: doc-xor
 4508: doc-invert
 4509: doc-lshift
 4510: doc-rshift
 4511: doc-2*
 4512: doc-d2*
 4513: doc-2/
 4514: doc-d2/
 4515: 
 4516: 
 4517: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4518: @subsection Numeric comparison
 4519: @cindex numeric comparison words
 4520: 
 4521: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4522: d0= d0<>}) work for for both signed and unsigned numbers.
 4523: 
 4524: doc-<
 4525: doc-<=
 4526: doc-<>
 4527: doc-=
 4528: doc->
 4529: doc->=
 4530: 
 4531: doc-0<
 4532: doc-0<=
 4533: doc-0<>
 4534: doc-0=
 4535: doc-0>
 4536: doc-0>=
 4537: 
 4538: doc-u<
 4539: doc-u<=
 4540: @c u<> and u= exist but are the same as <> and =
 4541: @c doc-u<>
 4542: @c doc-u=
 4543: doc-u>
 4544: doc-u>=
 4545: 
 4546: doc-within
 4547: 
 4548: doc-d<
 4549: doc-d<=
 4550: doc-d<>
 4551: doc-d=
 4552: doc-d>
 4553: doc-d>=
 4554: 
 4555: doc-d0<
 4556: doc-d0<=
 4557: doc-d0<>
 4558: doc-d0=
 4559: doc-d0>
 4560: doc-d0>=
 4561: 
 4562: doc-du<
 4563: doc-du<=
 4564: @c du<> and du= exist but are the same as d<> and d=
 4565: @c doc-du<>
 4566: @c doc-du=
 4567: doc-du>
 4568: doc-du>=
 4569: 
 4570: 
 4571: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4572: @subsection Mixed precision
 4573: @cindex mixed precision arithmetic words
 4574: 
 4575: 
 4576: doc-m+
 4577: doc-*/
 4578: doc-*/mod
 4579: doc-m*
 4580: doc-um*
 4581: doc-m*/
 4582: doc-um/mod
 4583: doc-fm/mod
 4584: doc-sm/rem
 4585: 
 4586: 
 4587: @node Floating Point,  , Mixed precision, Arithmetic
 4588: @subsection Floating Point
 4589: @cindex floating point arithmetic words
 4590: 
 4591: For the rules used by the text interpreter for
 4592: recognising floating-point numbers see @ref{Number Conversion}.
 4593: 
 4594: Gforth has a separate floating point stack, but the documentation uses
 4595: the unified notation.@footnote{It's easy to generate the separate
 4596: notation from that by just separating the floating-point numbers out:
 4597: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4598: r3 )}.}
 4599: 
 4600: @cindex floating-point arithmetic, pitfalls
 4601: Floating point numbers have a number of unpleasant surprises for the
 4602: unwary (e.g., floating point addition is not associative) and even a few
 4603: for the wary. You should not use them unless you know what you are doing
 4604: or you don't care that the results you get are totally bogus. If you
 4605: want to learn about the problems of floating point numbers (and how to
 4606: avoid them), you might start with @cite{David Goldberg,
 4607: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
 4608: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
 4609: Surveys 23(1):5@minus{}48, March 1991}.
 4610: 
 4611: 
 4612: doc-d>f
 4613: doc-f>d
 4614: doc-f+
 4615: doc-f-
 4616: doc-f*
 4617: doc-f/
 4618: doc-fnegate
 4619: doc-fabs
 4620: doc-fmax
 4621: doc-fmin
 4622: doc-floor
 4623: doc-fround
 4624: doc-f**
 4625: doc-fsqrt
 4626: doc-fexp
 4627: doc-fexpm1
 4628: doc-fln
 4629: doc-flnp1
 4630: doc-flog
 4631: doc-falog
 4632: doc-f2*
 4633: doc-f2/
 4634: doc-1/f
 4635: doc-precision
 4636: doc-set-precision
 4637: 
 4638: @cindex angles in trigonometric operations
 4639: @cindex trigonometric operations
 4640: Angles in floating point operations are given in radians (a full circle
 4641: has 2 pi radians).
 4642: 
 4643: doc-fsin
 4644: doc-fcos
 4645: doc-fsincos
 4646: doc-ftan
 4647: doc-fasin
 4648: doc-facos
 4649: doc-fatan
 4650: doc-fatan2
 4651: doc-fsinh
 4652: doc-fcosh
 4653: doc-ftanh
 4654: doc-fasinh
 4655: doc-facosh
 4656: doc-fatanh
 4657: doc-pi
 4658: 
 4659: @cindex equality of floats
 4660: @cindex floating-point comparisons
 4661: One particular problem with floating-point arithmetic is that comparison
 4662: for equality often fails when you would expect it to succeed.  For this
 4663: reason approximate equality is often preferred (but you still have to
 4664: know what you are doing).  Also note that IEEE NaNs may compare
 4665: differently from what you might expect.  The comparison words are:
 4666: 
 4667: doc-f~rel
 4668: doc-f~abs
 4669: doc-f~
 4670: doc-f=
 4671: doc-f<>
 4672: 
 4673: doc-f<
 4674: doc-f<=
 4675: doc-f>
 4676: doc-f>=
 4677: 
 4678: doc-f0<
 4679: doc-f0<=
 4680: doc-f0<>
 4681: doc-f0=
 4682: doc-f0>
 4683: doc-f0>=
 4684: 
 4685: 
 4686: @node Stack Manipulation, Memory, Arithmetic, Words
 4687: @section Stack Manipulation
 4688: @cindex stack manipulation words
 4689: 
 4690: @cindex floating-point stack in the standard
 4691: Gforth maintains a number of separate stacks:
 4692: 
 4693: @cindex data stack
 4694: @cindex parameter stack
 4695: @itemize @bullet
 4696: @item
 4697: A data stack (also known as the @dfn{parameter stack}) -- for
 4698: characters, cells, addresses, and double cells.
 4699: 
 4700: @cindex floating-point stack
 4701: @item
 4702: A floating point stack -- for holding floating point (FP) numbers.
 4703: 
 4704: @cindex return stack
 4705: @item
 4706: A return stack -- for holding the return addresses of colon
 4707: definitions and other (non-FP) data.
 4708: 
 4709: @cindex locals stack
 4710: @item
 4711: A locals stack -- for holding local variables.
 4712: @end itemize
 4713: 
 4714: @menu
 4715: * Data stack::                  
 4716: * Floating point stack::        
 4717: * Return stack::                
 4718: * Locals stack::                
 4719: * Stack pointer manipulation::  
 4720: @end menu
 4721: 
 4722: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4723: @subsection Data stack
 4724: @cindex data stack manipulation words
 4725: @cindex stack manipulations words, data stack
 4726: 
 4727: 
 4728: doc-drop
 4729: doc-nip
 4730: doc-dup
 4731: doc-over
 4732: doc-tuck
 4733: doc-swap
 4734: doc-pick
 4735: doc-rot
 4736: doc--rot
 4737: doc-?dup
 4738: doc-roll
 4739: doc-2drop
 4740: doc-2nip
 4741: doc-2dup
 4742: doc-2over
 4743: doc-2tuck
 4744: doc-2swap
 4745: doc-2rot
 4746: 
 4747: 
 4748: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4749: @subsection Floating point stack
 4750: @cindex floating-point stack manipulation words
 4751: @cindex stack manipulation words, floating-point stack
 4752: 
 4753: Whilst every sane Forth has a separate floating-point stack, it is not
 4754: strictly required; an ANS Forth system could theoretically keep
 4755: floating-point numbers on the data stack. As an additional difficulty,
 4756: you don't know how many cells a floating-point number takes. It is
 4757: reportedly possible to write words in a way that they work also for a
 4758: unified stack model, but we do not recommend trying it. Instead, just
 4759: say that your program has an environmental dependency on a separate
 4760: floating-point stack.
 4761: 
 4762: doc-floating-stack
 4763: 
 4764: doc-fdrop
 4765: doc-fnip
 4766: doc-fdup
 4767: doc-fover
 4768: doc-ftuck
 4769: doc-fswap
 4770: doc-fpick
 4771: doc-frot
 4772: 
 4773: 
 4774: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4775: @subsection Return stack
 4776: @cindex return stack manipulation words
 4777: @cindex stack manipulation words, return stack
 4778: 
 4779: @cindex return stack and locals
 4780: @cindex locals and return stack
 4781: A Forth system is allowed to keep local variables on the
 4782: return stack. This is reasonable, as local variables usually eliminate
 4783: the need to use the return stack explicitly. So, if you want to produce
 4784: a standard compliant program and you are using local variables in a
 4785: word, forget about return stack manipulations in that word (refer to the
 4786: standard document for the exact rules).
 4787: 
 4788: doc->r
 4789: doc-r>
 4790: doc-r@
 4791: doc-rdrop
 4792: doc-2>r
 4793: doc-2r>
 4794: doc-2r@
 4795: doc-2rdrop
 4796: 
 4797: 
 4798: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4799: @subsection Locals stack
 4800: 
 4801: Gforth uses an extra locals stack.  It is described, along with the
 4802: reasons for its existence, in @ref{Locals implementation}.
 4803: 
 4804: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4805: @subsection Stack pointer manipulation
 4806: @cindex stack pointer manipulation words
 4807: 
 4808: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 4809: doc-sp0
 4810: doc-sp@
 4811: doc-sp!
 4812: doc-fp0
 4813: doc-fp@
 4814: doc-fp!
 4815: doc-rp0
 4816: doc-rp@
 4817: doc-rp!
 4818: doc-lp0
 4819: doc-lp@
 4820: doc-lp!
 4821: 
 4822: 
 4823: @node Memory, Control Structures, Stack Manipulation, Words
 4824: @section Memory
 4825: @cindex memory words
 4826: 
 4827: @menu
 4828: * Memory model::                
 4829: * Dictionary allocation::       
 4830: * Heap Allocation::             
 4831: * Memory Access::               
 4832: * Address arithmetic::          
 4833: * Memory Blocks::               
 4834: @end menu
 4835: 
 4836: In addition to the standard Forth memory allocation words, there is also
 4837: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 4838: garbage collector}.
 4839: 
 4840: @node Memory model, Dictionary allocation, Memory, Memory
 4841: @subsection ANS Forth and Gforth memory models
 4842: 
 4843: @c The ANS Forth description is a mess (e.g., is the heap part of
 4844: @c the dictionary?), so let's not stick to closely with it.
 4845: 
 4846: ANS Forth considers a Forth system as consisting of several address
 4847: spaces, of which only @dfn{data space} is managed and accessible with
 4848: the memory words.  Memory not necessarily in data space includes the
 4849: stacks, the code (called code space) and the headers (called name
 4850: space). In Gforth everything is in data space, but the code for the
 4851: primitives is usually read-only.
 4852: 
 4853: Data space is divided into a number of areas: The (data space portion of
 4854: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 4855: refer to the search data structure embodied in word lists and headers,
 4856: because it is used for looking up names, just as you would in a
 4857: conventional dictionary.}, the heap, and a number of system-allocated
 4858: buffers.
 4859: 
 4860: @cindex address arithmetic restrictions, ANS vs. Gforth
 4861: @cindex contiguous regions, ANS vs. Gforth
 4862: In ANS Forth data space is also divided into contiguous regions.  You
 4863: can only use address arithmetic within a contiguous region, not between
 4864: them.  Usually each allocation gives you one contiguous region, but the
 4865: dictionary allocation words have additional rules (@pxref{Dictionary
 4866: allocation}).
 4867: 
 4868: Gforth provides one big address space, and address arithmetic can be
 4869: performed between any addresses. However, in the dictionary headers or
 4870: code are interleaved with data, so almost the only contiguous data space
 4871: regions there are those described by ANS Forth as contiguous; but you
 4872: can be sure that the dictionary is allocated towards increasing
 4873: addresses even between contiguous regions.  The memory order of
 4874: allocations in the heap is platform-dependent (and possibly different
 4875: from one run to the next).
 4876: 
 4877: 
 4878: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 4879: @subsection Dictionary allocation
 4880: @cindex reserving data space
 4881: @cindex data space - reserving some
 4882: 
 4883: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 4884: you want to deallocate X, you also deallocate everything
 4885: allocated after X.
 4886: 
 4887: @cindex contiguous regions in dictionary allocation
 4888: The allocations using the words below are contiguous and grow the region
 4889: towards increasing addresses.  Other words that allocate dictionary
 4890: memory of any kind (i.e., defining words including @code{:noname}) end
 4891: the contiguous region and start a new one.
 4892: 
 4893: In ANS Forth only @code{create}d words are guaranteed to produce an
 4894: address that is the start of the following contiguous region.  In
 4895: particular, the cell allocated by @code{variable} is not guaranteed to
 4896: be contiguous with following @code{allot}ed memory.
 4897: 
 4898: You can deallocate memory by using @code{allot} with a negative argument
 4899: (with some restrictions, see @code{allot}). For larger deallocations use
 4900: @code{marker}.
 4901: 
 4902: 
 4903: doc-here
 4904: doc-unused
 4905: doc-allot
 4906: doc-c,
 4907: doc-f,
 4908: doc-,
 4909: doc-2,
 4910: 
 4911: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 4912: course you should allocate memory in an aligned way, too. I.e., before
 4913: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 4914: The words below align @code{here} if it is not already.  Basically it is
 4915: only already aligned for a type, if the last allocation was a multiple
 4916: of the size of this type and if @code{here} was aligned for this type
 4917: before.
 4918: 
 4919: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 4920: ANS Forth (@code{maxalign}ed in Gforth).
 4921: 
 4922: doc-align
 4923: doc-falign
 4924: doc-sfalign
 4925: doc-dfalign
 4926: doc-maxalign
 4927: doc-cfalign
 4928: 
 4929: 
 4930: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 4931: @subsection Heap allocation
 4932: @cindex heap allocation
 4933: @cindex dynamic allocation of memory
 4934: @cindex memory-allocation word set
 4935: 
 4936: @cindex contiguous regions and heap allocation
 4937: Heap allocation supports deallocation of allocated memory in any
 4938: order. Dictionary allocation is not affected by it (i.e., it does not
 4939: end a contiguous region). In Gforth, these words are implemented using
 4940: the standard C library calls malloc(), free() and resize().
 4941: 
 4942: The memory region produced by one invocation of @code{allocate} or
 4943: @code{resize} is internally contiguous.  There is no contiguity between
 4944: such a region and any other region (including others allocated from the
 4945: heap).
 4946: 
 4947: doc-allocate
 4948: doc-free
 4949: doc-resize
 4950: 
 4951: 
 4952: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 4953: @subsection Memory Access
 4954: @cindex memory access words
 4955: 
 4956: doc-@
 4957: doc-!
 4958: doc-+!
 4959: doc-c@
 4960: doc-c!
 4961: doc-2@
 4962: doc-2!
 4963: doc-f@
 4964: doc-f!
 4965: doc-sf@
 4966: doc-sf!
 4967: doc-df@
 4968: doc-df!
 4969: 
 4970: 
 4971: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 4972: @subsection Address arithmetic
 4973: @cindex address arithmetic words
 4974: 
 4975: Address arithmetic is the foundation on which you can build data
 4976: structures like arrays, records (@pxref{Structures}) and objects
 4977: (@pxref{Object-oriented Forth}).
 4978: 
 4979: @cindex address unit
 4980: @cindex au (address unit)
 4981: ANS Forth does not specify the sizes of the data types. Instead, it
 4982: offers a number of words for computing sizes and doing address
 4983: arithmetic. Address arithmetic is performed in terms of address units
 4984: (aus); on most systems the address unit is one byte. Note that a
 4985: character may have more than one au, so @code{chars} is no noop (on
 4986: platforms where it is a noop, it compiles to nothing).
 4987: 
 4988: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 4989: you have the address of a cell, perform @code{1 cells +}, and you will
 4990: have the address of the next cell.
 4991: 
 4992: @cindex contiguous regions and address arithmetic
 4993: In ANS Forth you can perform address arithmetic only within a contiguous
 4994: region, i.e., if you have an address into one region, you can only add
 4995: and subtract such that the result is still within the region; you can
 4996: only subtract or compare addresses from within the same contiguous
 4997: region.  Reasons: several contiguous regions can be arranged in memory
 4998: in any way; on segmented systems addresses may have unusual
 4999: representations, such that address arithmetic only works within a
 5000: region.  Gforth provides a few more guarantees (linear address space,
 5001: dictionary grows upwards), but in general I have found it easy to stay
 5002: within contiguous regions (exception: computing and comparing to the
 5003: address just beyond the end of an array).
 5004: 
 5005: @cindex alignment of addresses for types
 5006: ANS Forth also defines words for aligning addresses for specific
 5007: types. Many computers require that accesses to specific data types
 5008: must only occur at specific addresses; e.g., that cells may only be
 5009: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5010: accesses, it can usually perform aligned accesses faster. 
 5011: 
 5012: For the performance-conscious: alignment operations are usually only
 5013: necessary during the definition of a data structure, not during the
 5014: (more frequent) accesses to it.
 5015: 
 5016: ANS Forth defines no words for character-aligning addresses. This is not
 5017: an oversight, but reflects the fact that addresses that are not
 5018: char-aligned have no use in the standard and therefore will not be
 5019: created.
 5020: 
 5021: @cindex @code{CREATE} and alignment
 5022: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5023: are cell-aligned; in addition, Gforth guarantees that these addresses
 5024: are aligned for all purposes.
 5025: 
 5026: Note that the ANS Forth word @code{char} has nothing to do with address
 5027: arithmetic.
 5028: 
 5029: 
 5030: doc-chars
 5031: doc-char+
 5032: doc-cells
 5033: doc-cell+
 5034: doc-cell
 5035: doc-aligned
 5036: doc-floats
 5037: doc-float+
 5038: doc-float
 5039: doc-faligned
 5040: doc-sfloats
 5041: doc-sfloat+
 5042: doc-sfaligned
 5043: doc-dfloats
 5044: doc-dfloat+
 5045: doc-dfaligned
 5046: doc-maxaligned
 5047: doc-cfaligned
 5048: doc-address-unit-bits
 5049: 
 5050: 
 5051: @node Memory Blocks,  , Address arithmetic, Memory
 5052: @subsection Memory Blocks
 5053: @cindex memory block words
 5054: @cindex character strings - moving and copying
 5055: 
 5056: Memory blocks often represent character strings; For ways of storing
 5057: character strings in memory see @ref{String Formats}.  For other
 5058: string-processing words see @ref{Displaying characters and strings}.
 5059: 
 5060: A few of these words work on address unit blocks.  In that case, you
 5061: usually have to insert @code{CHARS} before the word when working on
 5062: character strings.  Most words work on character blocks, and expect a
 5063: char-aligned address.
 5064: 
 5065: When copying characters between overlapping memory regions, use
 5066: @code{chars move} or choose carefully between @code{cmove} and
 5067: @code{cmove>}.
 5068: 
 5069: doc-move
 5070: doc-erase
 5071: doc-cmove
 5072: doc-cmove>
 5073: doc-fill
 5074: doc-blank
 5075: doc-compare
 5076: doc-str=
 5077: doc-str<
 5078: doc-string-prefix?
 5079: doc-search
 5080: doc--trailing
 5081: doc-/string
 5082: doc-bounds
 5083: 
 5084: 
 5085: @comment TODO examples
 5086: 
 5087: 
 5088: @node Control Structures, Defining Words, Memory, Words
 5089: @section Control Structures
 5090: @cindex control structures
 5091: 
 5092: Control structures in Forth cannot be used interpretively, only in a
 5093: colon definition@footnote{To be precise, they have no interpretation
 5094: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5095: not like this limitation, but have not seen a satisfying way around it
 5096: yet, although many schemes have been proposed.
 5097: 
 5098: @menu
 5099: * Selection::                   IF ... ELSE ... ENDIF
 5100: * Simple Loops::                BEGIN ...
 5101: * Counted Loops::               DO
 5102: * Arbitrary control structures::  
 5103: * Calls and returns::           
 5104: * Exception Handling::          
 5105: @end menu
 5106: 
 5107: @node Selection, Simple Loops, Control Structures, Control Structures
 5108: @subsection Selection
 5109: @cindex selection control structures
 5110: @cindex control structures for selection
 5111: 
 5112: @cindex @code{IF} control structure
 5113: @example
 5114: @i{flag}
 5115: IF
 5116:   @i{code}
 5117: ENDIF
 5118: @end example
 5119: @noindent
 5120: 
 5121: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5122: with any bit set represents truth) @i{code} is executed.
 5123: 
 5124: @example
 5125: @i{flag}
 5126: IF
 5127:   @i{code1}
 5128: ELSE
 5129:   @i{code2}
 5130: ENDIF
 5131: @end example
 5132: 
 5133: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5134: executed.
 5135: 
 5136: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5137: standard, and @code{ENDIF} is not, although it is quite popular. We
 5138: recommend using @code{ENDIF}, because it is less confusing for people
 5139: who also know other languages (and is not prone to reinforcing negative
 5140: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5141: system that only supplies @code{THEN} is simple:
 5142: @example
 5143: : ENDIF   POSTPONE then ; immediate
 5144: @end example
 5145: 
 5146: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5147: (adv.)}  has the following meanings:
 5148: @quotation
 5149: ... 2b: following next after in order ... 3d: as a necessary consequence
 5150: (if you were there, then you saw them).
 5151: @end quotation
 5152: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5153: and many other programming languages has the meaning 3d.]
 5154: 
 5155: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5156: you can avoid using @code{?dup}. Using these alternatives is also more
 5157: efficient than using @code{?dup}. Definitions in ANS Forth
 5158: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5159: @file{compat/control.fs}.
 5160: 
 5161: @cindex @code{CASE} control structure
 5162: @example
 5163: @i{n}
 5164: CASE
 5165:   @i{n1} OF @i{code1} ENDOF
 5166:   @i{n2} OF @i{code2} ENDOF
 5167:   @dots{}
 5168:   ( n ) @i{default-code} ( n )
 5169: ENDCASE
 5170: @end example
 5171: 
 5172: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
 5173: @i{ni} matches, the optional @i{default-code} is executed. The optional
 5174: default case can be added by simply writing the code after the last
 5175: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
 5176: not consume it.
 5177: 
 5178: @progstyle
 5179: To keep the code understandable, you should ensure that on all paths
 5180: through a selection construct the stack is changed in the same way
 5181: (wrt. number and types of stack items consumed and pushed).
 5182: 
 5183: @node Simple Loops, Counted Loops, Selection, Control Structures
 5184: @subsection Simple Loops
 5185: @cindex simple loops
 5186: @cindex loops without count 
 5187: 
 5188: @cindex @code{WHILE} loop
 5189: @example
 5190: BEGIN
 5191:   @i{code1}
 5192:   @i{flag}
 5193: WHILE
 5194:   @i{code2}
 5195: REPEAT
 5196: @end example
 5197: 
 5198: @i{code1} is executed and @i{flag} is computed. If it is true,
 5199: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5200: false, execution continues after the @code{REPEAT}.
 5201: 
 5202: @cindex @code{UNTIL} loop
 5203: @example
 5204: BEGIN
 5205:   @i{code}
 5206:   @i{flag}
 5207: UNTIL
 5208: @end example
 5209: 
 5210: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5211: 
 5212: @progstyle
 5213: To keep the code understandable, a complete iteration of the loop should
 5214: not change the number and types of the items on the stacks.
 5215: 
 5216: @cindex endless loop
 5217: @cindex loops, endless
 5218: @example
 5219: BEGIN
 5220:   @i{code}
 5221: AGAIN
 5222: @end example
 5223: 
 5224: This is an endless loop.
 5225: 
 5226: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5227: @subsection Counted Loops
 5228: @cindex counted loops
 5229: @cindex loops, counted
 5230: @cindex @code{DO} loops
 5231: 
 5232: The basic counted loop is:
 5233: @example
 5234: @i{limit} @i{start}
 5235: ?DO
 5236:   @i{body}
 5237: LOOP
 5238: @end example
 5239: 
 5240: This performs one iteration for every integer, starting from @i{start}
 5241: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5242: accessed with @code{i}. For example, the loop:
 5243: @example
 5244: 10 0 ?DO
 5245:   i .
 5246: LOOP
 5247: @end example
 5248: @noindent
 5249: prints @code{0 1 2 3 4 5 6 7 8 9}
 5250: 
 5251: The index of the innermost loop can be accessed with @code{i}, the index
 5252: of the next loop with @code{j}, and the index of the third loop with
 5253: @code{k}.
 5254: 
 5255: 
 5256: doc-i
 5257: doc-j
 5258: doc-k
 5259: 
 5260: 
 5261: The loop control data are kept on the return stack, so there are some
 5262: restrictions on mixing return stack accesses and counted loop words. In
 5263: particuler, if you put values on the return stack outside the loop, you
 5264: cannot read them inside the loop@footnote{well, not in a way that is
 5265: portable.}. If you put values on the return stack within a loop, you
 5266: have to remove them before the end of the loop and before accessing the
 5267: index of the loop.
 5268: 
 5269: There are several variations on the counted loop:
 5270: 
 5271: @itemize @bullet
 5272: @item
 5273: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5274: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5275: 
 5276: @example
 5277: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5278: @end example
 5279: prints @code{0 1 2 3}
 5280: 
 5281: 
 5282: @item
 5283: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5284: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5285: return stack so @code{EXIT} can get to its return address. For example:
 5286: 
 5287: @example
 5288: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5289: @end example
 5290: prints @code{0 1 2 3}
 5291: 
 5292: 
 5293: @item
 5294: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5295: (and @code{LOOP} iterates until they become equal by wrap-around
 5296: arithmetic). This behaviour is usually not what you want. Therefore,
 5297: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5298: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5299: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5300: unsigned loop parameters.
 5301: 
 5302: @item
 5303: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5304: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5305: if you know that the loop is entered in any case. Such knowledge tends
 5306: to become invalid during maintenance of a program, and then the
 5307: @code{DO} will make trouble.
 5308: 
 5309: @item
 5310: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5311: index by @i{n} instead of by 1. The loop is terminated when the border
 5312: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5313: 
 5314: @example
 5315: 4 0 +DO  i .  2 +LOOP
 5316: @end example
 5317: @noindent
 5318: prints @code{0 2}
 5319: 
 5320: @example
 5321: 4 1 +DO  i .  2 +LOOP
 5322: @end example
 5323: @noindent
 5324: prints @code{1 3}
 5325: 
 5326: @item
 5327: @cindex negative increment for counted loops
 5328: @cindex counted loops with negative increment
 5329: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5330: 
 5331: @example
 5332: -1 0 ?DO  i .  -1 +LOOP
 5333: @end example
 5334: @noindent
 5335: prints @code{0 -1}
 5336: 
 5337: @example
 5338: 0 0 ?DO  i .  -1 +LOOP
 5339: @end example
 5340: prints nothing.
 5341: 
 5342: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5343: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5344: index by @i{u} each iteration. The loop is terminated when the border
 5345: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5346: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5347: 
 5348: @example
 5349: -2 0 -DO  i .  1 -LOOP
 5350: @end example
 5351: @noindent
 5352: prints @code{0 -1}
 5353: 
 5354: @example
 5355: -1 0 -DO  i .  1 -LOOP
 5356: @end example
 5357: @noindent
 5358: prints @code{0}
 5359: 
 5360: @example
 5361: 0 0 -DO  i .  1 -LOOP
 5362: @end example
 5363: @noindent
 5364: prints nothing.
 5365: 
 5366: @end itemize
 5367: 
 5368: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5369: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5370: for these words that uses only standard words is provided in
 5371: @file{compat/loops.fs}.
 5372: 
 5373: 
 5374: @cindex @code{FOR} loops
 5375: Another counted loop is:
 5376: @example
 5377: @i{n}
 5378: FOR
 5379:   @i{body}
 5380: NEXT
 5381: @end example
 5382: This is the preferred loop of native code compiler writers who are too
 5383: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5384: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5385: @code{i} produces values starting with @i{n} and ending with 0. Other
 5386: Forth systems may behave differently, even if they support @code{FOR}
 5387: loops. To avoid problems, don't use @code{FOR} loops.
 5388: 
 5389: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5390: @subsection Arbitrary control structures
 5391: @cindex control structures, user-defined
 5392: 
 5393: @cindex control-flow stack
 5394: ANS Forth permits and supports using control structures in a non-nested
 5395: way. Information about incomplete control structures is stored on the
 5396: control-flow stack. This stack may be implemented on the Forth data
 5397: stack, and this is what we have done in Gforth.
 5398: 
 5399: @cindex @code{orig}, control-flow stack item
 5400: @cindex @code{dest}, control-flow stack item
 5401: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5402: entry represents a backward branch target. A few words are the basis for
 5403: building any control structure possible (except control structures that
 5404: need storage, like calls, coroutines, and backtracking).
 5405: 
 5406: 
 5407: doc-if
 5408: doc-ahead
 5409: doc-then
 5410: doc-begin
 5411: doc-until
 5412: doc-again
 5413: doc-cs-pick
 5414: doc-cs-roll
 5415: 
 5416: 
 5417: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5418: manipulate the control-flow stack in a portable way. Without them, you
 5419: would need to know how many stack items are occupied by a control-flow
 5420: entry (many systems use one cell. In Gforth they currently take three,
 5421: but this may change in the future).
 5422: 
 5423: Some standard control structure words are built from these words:
 5424: 
 5425: 
 5426: doc-else
 5427: doc-while
 5428: doc-repeat
 5429: 
 5430: 
 5431: @noindent
 5432: Gforth adds some more control-structure words:
 5433: 
 5434: 
 5435: doc-endif
 5436: doc-?dup-if
 5437: doc-?dup-0=-if
 5438: 
 5439: 
 5440: @noindent
 5441: Counted loop words constitute a separate group of words:
 5442: 
 5443: 
 5444: doc-?do
 5445: doc-+do
 5446: doc-u+do
 5447: doc--do
 5448: doc-u-do
 5449: doc-do
 5450: doc-for
 5451: doc-loop
 5452: doc-+loop
 5453: doc--loop
 5454: doc-next
 5455: doc-leave
 5456: doc-?leave
 5457: doc-unloop
 5458: doc-done
 5459: 
 5460: 
 5461: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5462: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5463: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5464: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5465: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5466: resolved (by using one of the loop-ending words or @code{DONE}).
 5467: 
 5468: @noindent
 5469: Another group of control structure words are:
 5470: 
 5471: 
 5472: doc-case
 5473: doc-endcase
 5474: doc-of
 5475: doc-endof
 5476: 
 5477: 
 5478: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5479: @code{CS-ROLL}.
 5480: 
 5481: @subsubsection Programming Style
 5482: @cindex control structures programming style
 5483: @cindex programming style, arbitrary control structures
 5484: 
 5485: In order to ensure readability we recommend that you do not create
 5486: arbitrary control structures directly, but define new control structure
 5487: words for the control structure you want and use these words in your
 5488: program. For example, instead of writing:
 5489: 
 5490: @example
 5491: BEGIN
 5492:   ...
 5493: IF [ 1 CS-ROLL ]
 5494:   ...
 5495: AGAIN THEN
 5496: @end example
 5497: 
 5498: @noindent
 5499: we recommend defining control structure words, e.g.,
 5500: 
 5501: @example
 5502: : WHILE ( DEST -- ORIG DEST )
 5503:  POSTPONE IF
 5504:  1 CS-ROLL ; immediate
 5505: 
 5506: : REPEAT ( orig dest -- )
 5507:  POSTPONE AGAIN
 5508:  POSTPONE THEN ; immediate
 5509: @end example
 5510: 
 5511: @noindent
 5512: and then using these to create the control structure:
 5513: 
 5514: @example
 5515: BEGIN
 5516:   ...
 5517: WHILE
 5518:   ...
 5519: REPEAT
 5520: @end example
 5521: 
 5522: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5523: @code{WHILE} are predefined, so in this example it would not be
 5524: necessary to define them.
 5525: 
 5526: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5527: @subsection Calls and returns
 5528: @cindex calling a definition
 5529: @cindex returning from a definition
 5530: 
 5531: @cindex recursive definitions
 5532: A definition can be called simply be writing the name of the definition
 5533: to be called. Normally a definition is invisible during its own
 5534: definition. If you want to write a directly recursive definition, you
 5535: can use @code{recursive} to make the current definition visible, or
 5536: @code{recurse} to call the current definition directly.
 5537: 
 5538: 
 5539: doc-recursive
 5540: doc-recurse
 5541: 
 5542: 
 5543: @comment TODO add example of the two recursion methods
 5544: @quotation
 5545: @progstyle
 5546: I prefer using @code{recursive} to @code{recurse}, because calling the
 5547: definition by name is more descriptive (if the name is well-chosen) than
 5548: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5549: implementation, it is much better to read (and think) ``now sort the
 5550: partitions'' than to read ``now do a recursive call''.
 5551: @end quotation
 5552: 
 5553: For mutual recursion, use @code{Defer}red words, like this:
 5554: 
 5555: @example
 5556: Defer foo
 5557: 
 5558: : bar ( ... -- ... )
 5559:  ... foo ... ;
 5560: 
 5561: :noname ( ... -- ... )
 5562:  ... bar ... ;
 5563: IS foo
 5564: @end example
 5565: 
 5566: Deferred words are discussed in more detail in @ref{Deferred words}.
 5567: 
 5568: The current definition returns control to the calling definition when
 5569: the end of the definition is reached or @code{EXIT} is encountered.
 5570: 
 5571: doc-exit
 5572: doc-;s
 5573: 
 5574: 
 5575: @node Exception Handling,  , Calls and returns, Control Structures
 5576: @subsection Exception Handling
 5577: @cindex exceptions
 5578: 
 5579: @c quit is a very bad idea for error handling, 
 5580: @c because it does not translate into a THROW
 5581: @c it also does not belong into this chapter
 5582: 
 5583: If a word detects an error condition that it cannot handle, it can
 5584: @code{throw} an exception.  In the simplest case, this will terminate
 5585: your program, and report an appropriate error.
 5586: 
 5587: doc-throw
 5588: 
 5589: @code{Throw} consumes a cell-sized error number on the stack. There are
 5590: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5591: Gforth (and most other systems) you can use the iors produced by various
 5592: words as error numbers (e.g., a typical use of @code{allocate} is
 5593: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5594: to define your own error numbers (with decent error reporting); an ANS
 5595: Forth version of this word (but without the error messages) is available
 5596: in @code{compat/except.fs}.  And finally, you can use your own error
 5597: numbers (anything outside the range -4095..0), but won't get nice error
 5598: messages, only numbers.  For example, try:
 5599: 
 5600: @example
 5601: -10 throw                    \ ANS defined
 5602: -267 throw                   \ system defined
 5603: s" my error" exception throw \ user defined
 5604: 7 throw                      \ arbitrary number
 5605: @end example
 5606: 
 5607: doc---exception-exception
 5608: 
 5609: A common idiom to @code{THROW} a specific error if a flag is true is
 5610: this:
 5611: 
 5612: @example
 5613: @code{( flag ) 0<> @i{errno} and throw}
 5614: @end example
 5615: 
 5616: Your program can provide exception handlers to catch exceptions.  An
 5617: exception handler can be used to correct the problem, or to clean up
 5618: some data structures and just throw the exception to the next exception
 5619: handler.  Note that @code{throw} jumps to the dynamically innermost
 5620: exception handler.  The system's exception handler is outermost, and just
 5621: prints an error and restarts command-line interpretation (or, in batch
 5622: mode (i.e., while processing the shell command line), leaves Gforth).
 5623: 
 5624: The ANS Forth way to catch exceptions is @code{catch}:
 5625: 
 5626: doc-catch
 5627: 
 5628: The most common use of exception handlers is to clean up the state when
 5629: an error happens.  E.g.,
 5630: 
 5631: @example
 5632: base @ >r hex \ actually the hex should be inside foo, or we h
 5633: ['] foo catch ( nerror|0 )
 5634: r> base !
 5635: ( nerror|0 ) throw \ pass it on
 5636: @end example
 5637: 
 5638: A use of @code{catch} for handling the error @code{myerror} might look
 5639: like this:
 5640: 
 5641: @example
 5642: ['] foo catch
 5643: CASE
 5644:   myerror OF ... ( do something about it ) ENDOF
 5645:   dup throw \ default: pass other errors on, do nothing on non-errors
 5646: ENDCASE
 5647: @end example
 5648: 
 5649: Having to wrap the code into a separate word is often cumbersome,
 5650: therefore Gforth provides an alternative syntax:
 5651: 
 5652: @example
 5653: TRY
 5654:   @i{code1}
 5655: RECOVER     \ optional
 5656:   @i{code2} \ optional
 5657: ENDTRY
 5658: @end example
 5659: 
 5660: This performs @i{Code1}.  If @i{code1} completes normally, execution
 5661: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
 5662: reset to the state during @code{try}, the throw value is pushed on the
 5663: data stack, and execution constinues at @i{code2}, and finally falls
 5664: through the @code{endtry} into the following code.
 5665: 
 5666: doc-try
 5667: doc-recover
 5668: doc-endtry
 5669: 
 5670: The cleanup example from above in this syntax:
 5671: 
 5672: @example
 5673: base @ >r TRY
 5674:   hex foo \ now the hex is placed correctly
 5675:   0       \ value for throw
 5676: RECOVER ENDTRY
 5677: r> base ! throw
 5678: @end example
 5679: 
 5680: And here's the error handling example:
 5681: 
 5682: @example
 5683: TRY
 5684:   foo
 5685: RECOVER
 5686:   CASE
 5687:     myerror OF ... ( do something about it ) ENDOF
 5688:     throw \ pass other errors on
 5689:   ENDCASE
 5690: ENDTRY
 5691: @end example
 5692: 
 5693: @progstyle
 5694: As usual, you should ensure that the stack depth is statically known at
 5695: the end: either after the @code{throw} for passing on errors, or after
 5696: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5697: selection construct for handling the error).
 5698: 
 5699: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 5700: and you can provide an error message.  @code{Abort} just produces an
 5701: ``Aborted'' error.
 5702: 
 5703: The problem with these words is that exception handlers cannot
 5704: differentiate between different @code{abort"}s; they just look like
 5705: @code{-2 throw} to them (the error message cannot be accessed by
 5706: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 5707: exception handlers.
 5708: 
 5709: doc-abort"
 5710: doc-abort
 5711: 
 5712: 
 5713: 
 5714: @c -------------------------------------------------------------
 5715: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 5716: @section Defining Words
 5717: @cindex defining words
 5718: 
 5719: Defining words are used to extend Forth by creating new entries in the dictionary.
 5720: 
 5721: @menu
 5722: * CREATE::                      
 5723: * Variables::                   Variables and user variables
 5724: * Constants::                   
 5725: * Values::                      Initialised variables
 5726: * Colon Definitions::           
 5727: * Anonymous Definitions::       Definitions without names
 5728: * Supplying names::             Passing definition names as strings
 5729: * User-defined Defining Words::  
 5730: * Deferred words::              Allow forward references
 5731: * Aliases::                     
 5732: @end menu
 5733: 
 5734: @node CREATE, Variables, Defining Words, Defining Words
 5735: @subsection @code{CREATE}
 5736: @cindex simple defining words
 5737: @cindex defining words, simple
 5738: 
 5739: Defining words are used to create new entries in the dictionary. The
 5740: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 5741: this:
 5742: 
 5743: @example
 5744: CREATE new-word1
 5745: @end example
 5746: 
 5747: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 5748: input stream (@code{new-word1} in our example).  It generates a
 5749: dictionary entry for @code{new-word1}. When @code{new-word1} is
 5750: executed, all that it does is leave an address on the stack. The address
 5751: represents the value of the data space pointer (@code{HERE}) at the time
 5752: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 5753: associating a name with the address of a region of memory.
 5754: 
 5755: doc-create
 5756: 
 5757: Note that in ANS Forth guarantees only for @code{create} that its body
 5758: is in dictionary data space (i.e., where @code{here}, @code{allot}
 5759: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 5760: @code{create}d words can be modified with @code{does>}
 5761: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 5762: can only be applied to @code{create}d words.
 5763: 
 5764: By extending this example to reserve some memory in data space, we end
 5765: up with something like a @i{variable}. Here are two different ways to do
 5766: it:
 5767: 
 5768: @example
 5769: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 5770: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 5771: @end example
 5772: 
 5773: The variable can be examined and modified using @code{@@} (``fetch'') and
 5774: @code{!} (``store'') like this:
 5775: 
 5776: @example
 5777: new-word2 @@ .      \ get address, fetch from it and display
 5778: 1234 new-word2 !   \ new value, get address, store to it
 5779: @end example
 5780: 
 5781: @cindex arrays
 5782: A similar mechanism can be used to create arrays. For example, an
 5783: 80-character text input buffer:
 5784: 
 5785: @example
 5786: CREATE text-buf 80 chars allot
 5787: 
 5788: text-buf 0 chars c@@ \ the 1st character (offset 0)
 5789: text-buf 3 chars c@@ \ the 4th character (offset 3)
 5790: @end example
 5791: 
 5792: You can build arbitrarily complex data structures by allocating
 5793: appropriate areas of memory. For further discussions of this, and to
 5794: learn about some Gforth tools that make it easier,
 5795: @xref{Structures}.
 5796: 
 5797: 
 5798: @node Variables, Constants, CREATE, Defining Words
 5799: @subsection Variables
 5800: @cindex variables
 5801: 
 5802: The previous section showed how a sequence of commands could be used to
 5803: generate a variable.  As a final refinement, the whole code sequence can
 5804: be wrapped up in a defining word (pre-empting the subject of the next
 5805: section), making it easier to create new variables:
 5806: 
 5807: @example
 5808: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 5809: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 5810: 
 5811: myvariableX foo \ variable foo starts off with an unknown value
 5812: myvariable0 joe \ whilst joe is initialised to 0
 5813: 
 5814: 45 3 * foo !   \ set foo to 135
 5815: 1234 joe !     \ set joe to 1234
 5816: 3 joe +!       \ increment joe by 3.. to 1237
 5817: @end example
 5818: 
 5819: Not surprisingly, there is no need to define @code{myvariable}, since
 5820: Forth already has a definition @code{Variable}. ANS Forth does not
 5821: guarantee that a @code{Variable} is initialised when it is created
 5822: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 5823: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 5824: like @code{myvariable0}). Forth also provides @code{2Variable} and
 5825: @code{fvariable} for double and floating-point variables, respectively
 5826: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 5827: store a boolean, you can use @code{on} and @code{off} to toggle its
 5828: state.
 5829: 
 5830: doc-variable
 5831: doc-2variable
 5832: doc-fvariable
 5833: 
 5834: @cindex user variables
 5835: @cindex user space
 5836: The defining word @code{User} behaves in the same way as @code{Variable}.
 5837: The difference is that it reserves space in @i{user (data) space} rather
 5838: than normal data space. In a Forth system that has a multi-tasker, each
 5839: task has its own set of user variables.
 5840: 
 5841: doc-user
 5842: @c doc-udp
 5843: @c doc-uallot
 5844: 
 5845: @comment TODO is that stuff about user variables strictly correct? Is it
 5846: @comment just terminal tasks that have user variables?
 5847: @comment should document tasker.fs (with some examples) elsewhere
 5848: @comment in this manual, then expand on user space and user variables.
 5849: 
 5850: @node Constants, Values, Variables, Defining Words
 5851: @subsection Constants
 5852: @cindex constants
 5853: 
 5854: @code{Constant} allows you to declare a fixed value and refer to it by
 5855: name. For example:
 5856: 
 5857: @example
 5858: 12 Constant INCHES-PER-FOOT
 5859: 3E+08 fconstant SPEED-O-LIGHT
 5860: @end example
 5861: 
 5862: A @code{Variable} can be both read and written, so its run-time
 5863: behaviour is to supply an address through which its current value can be
 5864: manipulated. In contrast, the value of a @code{Constant} cannot be
 5865: changed once it has been declared@footnote{Well, often it can be -- but
 5866: not in a Standard, portable way. It's safer to use a @code{Value} (read
 5867: on).} so it's not necessary to supply the address -- it is more
 5868: efficient to return the value of the constant directly. That's exactly
 5869: what happens; the run-time effect of a constant is to put its value on
 5870: the top of the stack (You can find one
 5871: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 5872: 
 5873: Forth also provides @code{2Constant} and @code{fconstant} for defining
 5874: double and floating-point constants, respectively.
 5875: 
 5876: doc-constant
 5877: doc-2constant
 5878: doc-fconstant
 5879: 
 5880: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 5881: @c nac-> How could that not be true in an ANS Forth? You can't define a
 5882: @c constant, use it and then delete the definition of the constant..
 5883: 
 5884: @c anton->An ANS Forth system can compile a constant to a literal; On
 5885: @c decompilation you would see only the number, just as if it had been used
 5886: @c in the first place.  The word will stay, of course, but it will only be
 5887: @c used by the text interpreter (no run-time duties, except when it is 
 5888: @c POSTPONEd or somesuch).
 5889: 
 5890: @c nac:
 5891: @c I agree that it's rather deep, but IMO it is an important difference
 5892: @c relative to other programming languages.. often it's annoying: it
 5893: @c certainly changes my programming style relative to C.
 5894: 
 5895: @c anton: In what way?
 5896: 
 5897: Constants in Forth behave differently from their equivalents in other
 5898: programming languages. In other languages, a constant (such as an EQU in
 5899: assembler or a #define in C) only exists at compile-time; in the
 5900: executable program the constant has been translated into an absolute
 5901: number and, unless you are using a symbolic debugger, it's impossible to
 5902: know what abstract thing that number represents. In Forth a constant has
 5903: an entry in the header space and remains there after the code that uses
 5904: it has been defined. In fact, it must remain in the dictionary since it
 5905: has run-time duties to perform. For example:
 5906: 
 5907: @example
 5908: 12 Constant INCHES-PER-FOOT
 5909: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 5910: @end example
 5911: 
 5912: @cindex in-lining of constants
 5913: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 5914: associated with the constant @code{INCHES-PER-FOOT}. If you use
 5915: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 5916: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 5917: attempt to optimise constants by in-lining them where they are used. You
 5918: can force Gforth to in-line a constant like this:
 5919: 
 5920: @example
 5921: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 5922: @end example
 5923: 
 5924: If you use @code{see} to decompile @i{this} version of
 5925: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 5926: longer present. To understand how this works, read
 5927: @ref{Interpret/Compile states}, and @ref{Literals}.
 5928: 
 5929: In-lining constants in this way might improve execution time
 5930: fractionally, and can ensure that a constant is now only referenced at
 5931: compile-time. However, the definition of the constant still remains in
 5932: the dictionary. Some Forth compilers provide a mechanism for controlling
 5933: a second dictionary for holding transient words such that this second
 5934: dictionary can be deleted later in order to recover memory
 5935: space. However, there is no standard way of doing this.
 5936: 
 5937: 
 5938: @node Values, Colon Definitions, Constants, Defining Words
 5939: @subsection Values
 5940: @cindex values
 5941: 
 5942: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 5943: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 5944: (not in ANS Forth) you can access (and change) a @code{value} also with
 5945: @code{>body}.
 5946: 
 5947: Here are some
 5948: examples:
 5949: 
 5950: @example
 5951: 12 Value APPLES     \ Define APPLES with an initial value of 12
 5952: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 5953: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 5954: APPLES              \ puts 35 on the top of the stack.
 5955: @end example
 5956: 
 5957: doc-value
 5958: doc-to
 5959: 
 5960: 
 5961: 
 5962: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 5963: @subsection Colon Definitions
 5964: @cindex colon definitions
 5965: 
 5966: @example
 5967: : name ( ... -- ... )
 5968:     word1 word2 word3 ;
 5969: @end example
 5970: 
 5971: @noindent
 5972: Creates a word called @code{name} that, upon execution, executes
 5973: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 5974: 
 5975: The explanation above is somewhat superficial. For simple examples of
 5976: colon definitions see @ref{Your first definition}.  For an in-depth
 5977: discussion of some of the issues involved, @xref{Interpretation and
 5978: Compilation Semantics}.
 5979: 
 5980: doc-:
 5981: doc-;
 5982: 
 5983: 
 5984: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
 5985: @subsection Anonymous Definitions
 5986: @cindex colon definitions
 5987: @cindex defining words without name
 5988: 
 5989: Sometimes you want to define an @dfn{anonymous word}; a word without a
 5990: name. You can do this with:
 5991: 
 5992: doc-:noname
 5993: 
 5994: This leaves the execution token for the word on the stack after the
 5995: closing @code{;}. Here's an example in which a deferred word is
 5996: initialised with an @code{xt} from an anonymous colon definition:
 5997: 
 5998: @example
 5999: Defer deferred
 6000: :noname ( ... -- ... )
 6001:   ... ;
 6002: IS deferred
 6003: @end example
 6004: 
 6005: @noindent
 6006: Gforth provides an alternative way of doing this, using two separate
 6007: words:
 6008: 
 6009: doc-noname
 6010: @cindex execution token of last defined word
 6011: doc-latestxt
 6012: 
 6013: @noindent
 6014: The previous example can be rewritten using @code{noname} and
 6015: @code{latestxt}:
 6016: 
 6017: @example
 6018: Defer deferred
 6019: noname : ( ... -- ... )
 6020:   ... ;
 6021: latestxt IS deferred
 6022: @end example
 6023: 
 6024: @noindent
 6025: @code{noname} works with any defining word, not just @code{:}.
 6026: 
 6027: @code{latestxt} also works when the last word was not defined as
 6028: @code{noname}.  It does not work for combined words, though.  It also has
 6029: the useful property that is is valid as soon as the header for a
 6030: definition has been built. Thus:
 6031: 
 6032: @example
 6033: latestxt . : foo [ latestxt . ] ; ' foo .
 6034: @end example
 6035: 
 6036: @noindent
 6037: prints 3 numbers; the last two are the same.
 6038: 
 6039: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
 6040: @subsection Supplying the name of a defined word
 6041: @cindex names for defined words
 6042: @cindex defining words, name given in a string
 6043: 
 6044: By default, a defining word takes the name for the defined word from the
 6045: input stream. Sometimes you want to supply the name from a string. You
 6046: can do this with:
 6047: 
 6048: doc-nextname
 6049: 
 6050: For example:
 6051: 
 6052: @example
 6053: s" foo" nextname create
 6054: @end example
 6055: 
 6056: @noindent
 6057: is equivalent to:
 6058: 
 6059: @example
 6060: create foo
 6061: @end example
 6062: 
 6063: @noindent
 6064: @code{nextname} works with any defining word.
 6065: 
 6066: 
 6067: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
 6068: @subsection User-defined Defining Words
 6069: @cindex user-defined defining words
 6070: @cindex defining words, user-defined
 6071: 
 6072: You can create a new defining word by wrapping defining-time code around
 6073: an existing defining word and putting the sequence in a colon
 6074: definition. 
 6075: 
 6076: @c anton: This example is very complex and leads in a quite different
 6077: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6078: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6079: @c subsection of Defining Words)
 6080: 
 6081: For example, suppose that you have a word @code{stats} that
 6082: gathers statistics about colon definitions given the @i{xt} of the
 6083: definition, and you want every colon definition in your application to
 6084: make a call to @code{stats}. You can define and use a new version of
 6085: @code{:} like this:
 6086: 
 6087: @example
 6088: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6089:   ... ;  \ other code
 6090: 
 6091: : my: : latestxt postpone literal ['] stats compile, ;
 6092: 
 6093: my: foo + - ;
 6094: @end example
 6095: 
 6096: When @code{foo} is defined using @code{my:} these steps occur:
 6097: 
 6098: @itemize @bullet
 6099: @item
 6100: @code{my:} is executed.
 6101: @item
 6102: The @code{:} within the definition (the one between @code{my:} and
 6103: @code{latestxt}) is executed, and does just what it always does; it parses
 6104: the input stream for a name, builds a dictionary header for the name
 6105: @code{foo} and switches @code{state} from interpret to compile.
 6106: @item
 6107: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6108: being defined -- @code{foo} -- onto the stack.
 6109: @item
 6110: The code that was produced by @code{postpone literal} is executed; this
 6111: causes the value on the stack to be compiled as a literal in the code
 6112: area of @code{foo}.
 6113: @item
 6114: The code @code{['] stats} compiles a literal into the definition of
 6115: @code{my:}. When @code{compile,} is executed, that literal -- the
 6116: execution token for @code{stats} -- is layed down in the code area of
 6117: @code{foo} , following the literal@footnote{Strictly speaking, the
 6118: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6119: in the code area is implementation-dependent. A threaded implementation
 6120: might spit out the execution token directly whilst another
 6121: implementation might spit out a native code sequence.}.
 6122: @item
 6123: At this point, the execution of @code{my:} is complete, and control
 6124: returns to the text interpreter. The text interpreter is in compile
 6125: state, so subsequent text @code{+ -} is compiled into the definition of
 6126: @code{foo} and the @code{;} terminates the definition as always.
 6127: @end itemize
 6128: 
 6129: You can use @code{see} to decompile a word that was defined using
 6130: @code{my:} and see how it is different from a normal @code{:}
 6131: definition. For example:
 6132: 
 6133: @example
 6134: : bar + - ;  \ like foo but using : rather than my:
 6135: see bar
 6136: : bar
 6137:   + - ;
 6138: see foo
 6139: : foo
 6140:   107645672 stats + - ;
 6141: 
 6142: \ use ' stats . to show that 107645672 is the xt for stats
 6143: @end example
 6144: 
 6145: You can use techniques like this to make new defining words in terms of
 6146: @i{any} existing defining word.
 6147: 
 6148: 
 6149: @cindex defining defining words
 6150: @cindex @code{CREATE} ... @code{DOES>}
 6151: If you want the words defined with your defining words to behave
 6152: differently from words defined with standard defining words, you can
 6153: write your defining word like this:
 6154: 
 6155: @example
 6156: : def-word ( "name" -- )
 6157:     CREATE @i{code1}
 6158: DOES> ( ... -- ... )
 6159:     @i{code2} ;
 6160: 
 6161: def-word name
 6162: @end example
 6163: 
 6164: @cindex child words
 6165: This fragment defines a @dfn{defining word} @code{def-word} and then
 6166: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6167: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6168: is not executed at this time. The word @code{name} is sometimes called a
 6169: @dfn{child} of @code{def-word}.
 6170: 
 6171: When you execute @code{name}, the address of the body of @code{name} is
 6172: put on the data stack and @i{code2} is executed (the address of the body
 6173: of @code{name} is the address @code{HERE} returns immediately after the
 6174: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6175: default).
 6176: 
 6177: @c anton:
 6178: @c www.dictionary.com says:
 6179: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6180: @c several generations of absence, usually caused by the chance
 6181: @c recombination of genes.  2.An individual or a part that exhibits
 6182: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6183: @c of previous behavior after a period of absence.
 6184: @c
 6185: @c Doesn't seem to fit.
 6186: 
 6187: @c @cindex atavism in child words
 6188: You can use @code{def-word} to define a set of child words that behave
 6189: similarly; they all have a common run-time behaviour determined by
 6190: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6191: body of the child word. The structure of the data is common to all
 6192: children of @code{def-word}, but the data values are specific -- and
 6193: private -- to each child word. When a child word is executed, the
 6194: address of its private data area is passed as a parameter on TOS to be
 6195: used and manipulated@footnote{It is legitimate both to read and write to
 6196: this data area.} by @i{code2}.
 6197: 
 6198: The two fragments of code that make up the defining words act (are
 6199: executed) at two completely separate times:
 6200: 
 6201: @itemize @bullet
 6202: @item
 6203: At @i{define time}, the defining word executes @i{code1} to generate a
 6204: child word
 6205: @item
 6206: At @i{child execution time}, when a child word is invoked, @i{code2}
 6207: is executed, using parameters (data) that are private and specific to
 6208: the child word.
 6209: @end itemize
 6210: 
 6211: Another way of understanding the behaviour of @code{def-word} and
 6212: @code{name} is to say that, if you make the following definitions:
 6213: @example
 6214: : def-word1 ( "name" -- )
 6215:     CREATE @i{code1} ;
 6216: 
 6217: : action1 ( ... -- ... )
 6218:     @i{code2} ;
 6219: 
 6220: def-word1 name1
 6221: @end example
 6222: 
 6223: @noindent
 6224: Then using @code{name1 action1} is equivalent to using @code{name}.
 6225: 
 6226: The classic example is that you can define @code{CONSTANT} in this way:
 6227: 
 6228: @example
 6229: : CONSTANT ( w "name" -- )
 6230:     CREATE ,
 6231: DOES> ( -- w )
 6232:     @@ ;
 6233: @end example
 6234: 
 6235: @comment There is a beautiful description of how this works and what
 6236: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6237: @comment commentary on the Counting Fruits problem.
 6238: 
 6239: When you create a constant with @code{5 CONSTANT five}, a set of
 6240: define-time actions take place; first a new word @code{five} is created,
 6241: then the value 5 is laid down in the body of @code{five} with
 6242: @code{,}. When @code{five} is executed, the address of the body is put on
 6243: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6244: no code of its own; it simply contains a data field and a pointer to the
 6245: code that follows @code{DOES>} in its defining word. That makes words
 6246: created in this way very compact.
 6247: 
 6248: The final example in this section is intended to remind you that space
 6249: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6250: both read and written by a Standard program@footnote{Exercise: use this
 6251: example as a starting point for your own implementation of @code{Value}
 6252: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6253: @code{[']}.}:
 6254: 
 6255: @example
 6256: : foo ( "name" -- )
 6257:     CREATE -1 ,
 6258: DOES> ( -- )
 6259:     @@ . ;
 6260: 
 6261: foo first-word
 6262: foo second-word
 6263: 
 6264: 123 ' first-word >BODY !
 6265: @end example
 6266: 
 6267: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6268: have executed it to get the address of its data field. However, since it
 6269: was defined to have @code{DOES>} actions, its execution semantics are to
 6270: perform those @code{DOES>} actions. To get the address of its data field
 6271: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6272: translate the xt into the address of the data field.  When you execute
 6273: @code{first-word}, it will display @code{123}. When you execute
 6274: @code{second-word} it will display @code{-1}.
 6275: 
 6276: @cindex stack effect of @code{DOES>}-parts
 6277: @cindex @code{DOES>}-parts, stack effect
 6278: In the examples above the stack comment after the @code{DOES>} specifies
 6279: the stack effect of the defined words, not the stack effect of the
 6280: following code (the following code expects the address of the body on
 6281: the top of stack, which is not reflected in the stack comment). This is
 6282: the convention that I use and recommend (it clashes a bit with using
 6283: locals declarations for stack effect specification, though).
 6284: 
 6285: @menu
 6286: * CREATE..DOES> applications::  
 6287: * CREATE..DOES> details::       
 6288: * Advanced does> usage example::  
 6289: * @code{Const-does>}::          
 6290: @end menu
 6291: 
 6292: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6293: @subsubsection Applications of @code{CREATE..DOES>}
 6294: @cindex @code{CREATE} ... @code{DOES>}, applications
 6295: 
 6296: You may wonder how to use this feature. Here are some usage patterns:
 6297: 
 6298: @cindex factoring similar colon definitions
 6299: When you see a sequence of code occurring several times, and you can
 6300: identify a meaning, you will factor it out as a colon definition. When
 6301: you see similar colon definitions, you can factor them using
 6302: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6303: that look very similar:
 6304: @example
 6305: : ori, ( reg-target reg-source n -- )
 6306:     0 asm-reg-reg-imm ;
 6307: : andi, ( reg-target reg-source n -- )
 6308:     1 asm-reg-reg-imm ;
 6309: @end example
 6310: 
 6311: @noindent
 6312: This could be factored with:
 6313: @example
 6314: : reg-reg-imm ( op-code -- )
 6315:     CREATE ,
 6316: DOES> ( reg-target reg-source n -- )
 6317:     @@ asm-reg-reg-imm ;
 6318: 
 6319: 0 reg-reg-imm ori,
 6320: 1 reg-reg-imm andi,
 6321: @end example
 6322: 
 6323: @cindex currying
 6324: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6325: supply a part of the parameters for a word (known as @dfn{currying} in
 6326: the functional language community). E.g., @code{+} needs two
 6327: parameters. Creating versions of @code{+} with one parameter fixed can
 6328: be done like this:
 6329: 
 6330: @example
 6331: : curry+ ( n1 "name" -- )
 6332:     CREATE ,
 6333: DOES> ( n2 -- n1+n2 )
 6334:     @@ + ;
 6335: 
 6336:  3 curry+ 3+
 6337: -2 curry+ 2-
 6338: @end example
 6339: 
 6340: 
 6341: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6342: @subsubsection The gory details of @code{CREATE..DOES>}
 6343: @cindex @code{CREATE} ... @code{DOES>}, details
 6344: 
 6345: doc-does>
 6346: 
 6347: @cindex @code{DOES>} in a separate definition
 6348: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6349: same definition; you can put the @code{DOES>}-part in a separate
 6350: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6351: @example
 6352: : does1 
 6353: DOES> ( ... -- ... )
 6354:     ... ;
 6355: 
 6356: : does2
 6357: DOES> ( ... -- ... )
 6358:     ... ;
 6359: 
 6360: : def-word ( ... -- ... )
 6361:     create ...
 6362:     IF
 6363:        does1
 6364:     ELSE
 6365:        does2
 6366:     ENDIF ;
 6367: @end example
 6368: 
 6369: In this example, the selection of whether to use @code{does1} or
 6370: @code{does2} is made at definition-time; at the time that the child word is
 6371: @code{CREATE}d.
 6372: 
 6373: @cindex @code{DOES>} in interpretation state
 6374: In a standard program you can apply a @code{DOES>}-part only if the last
 6375: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6376: will override the behaviour of the last word defined in any case. In a
 6377: standard program, you can use @code{DOES>} only in a colon
 6378: definition. In Gforth, you can also use it in interpretation state, in a
 6379: kind of one-shot mode; for example:
 6380: @example
 6381: CREATE name ( ... -- ... )
 6382:   @i{initialization}
 6383: DOES>
 6384:   @i{code} ;
 6385: @end example
 6386: 
 6387: @noindent
 6388: is equivalent to the standard:
 6389: @example
 6390: :noname
 6391: DOES>
 6392:     @i{code} ;
 6393: CREATE name EXECUTE ( ... -- ... )
 6394:     @i{initialization}
 6395: @end example
 6396: 
 6397: doc->body
 6398: 
 6399: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
 6400: @subsubsection Advanced does> usage example
 6401: 
 6402: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6403: for disassembling instructions, that follow a very repetetive scheme:
 6404: 
 6405: @example
 6406: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6407: @var{entry-num} cells @var{table} + !
 6408: @end example
 6409: 
 6410: Of course, this inspires the idea to factor out the commonalities to
 6411: allow a definition like
 6412: 
 6413: @example
 6414: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6415: @end example
 6416: 
 6417: The parameters @var{disasm-operands} and @var{table} are usually
 6418: correlated.  Moreover, before I wrote the disassembler, there already
 6419: existed code that defines instructions like this:
 6420: 
 6421: @example
 6422: @var{entry-num} @var{inst-format} @var{inst-name}
 6423: @end example
 6424: 
 6425: This code comes from the assembler and resides in
 6426: @file{arch/mips/insts.fs}.
 6427: 
 6428: So I had to define the @var{inst-format} words that performed the scheme
 6429: above when executed.  At first I chose to use run-time code-generation:
 6430: 
 6431: @example
 6432: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6433:   :noname Postpone @var{disasm-operands}
 6434:   name Postpone sliteral Postpone type Postpone ;
 6435:   swap cells @var{table} + ! ;
 6436: @end example
 6437: 
 6438: Note that this supplies the other two parameters of the scheme above.
 6439: 
 6440: An alternative would have been to write this using
 6441: @code{create}/@code{does>}:
 6442: 
 6443: @example
 6444: : @var{inst-format} ( entry-num "name" -- )
 6445:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6446:   noname create , ( entry-num )
 6447:   latestxt swap cells @var{table} + !
 6448: does> ( addr w -- )
 6449:   \ disassemble instruction w at addr
 6450:   @@ >r 
 6451:   @var{disasm-operands}
 6452:   r> count type ;
 6453: @end example
 6454: 
 6455: Somehow the first solution is simpler, mainly because it's simpler to
 6456: shift a string from definition-time to use-time with @code{sliteral}
 6457: than with @code{string,} and friends.
 6458: 
 6459: I wrote a lot of words following this scheme and soon thought about
 6460: factoring out the commonalities among them.  Note that this uses a
 6461: two-level defining word, i.e., a word that defines ordinary defining
 6462: words.
 6463: 
 6464: This time a solution involving @code{postpone} and friends seemed more
 6465: difficult (try it as an exercise), so I decided to use a
 6466: @code{create}/@code{does>} word; since I was already at it, I also used
 6467: @code{create}/@code{does>} for the lower level (try using
 6468: @code{postpone} etc. as an exercise), resulting in the following
 6469: definition:
 6470: 
 6471: @example
 6472: : define-format ( disasm-xt table-xt -- )
 6473:     \ define an instruction format that uses disasm-xt for
 6474:     \ disassembling and enters the defined instructions into table
 6475:     \ table-xt
 6476:     create 2,
 6477: does> ( u "inst" -- )
 6478:     \ defines an anonymous word for disassembling instruction inst,
 6479:     \ and enters it as u-th entry into table-xt
 6480:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6481:     noname create 2,      \ define anonymous word
 6482:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6483: does> ( addr w -- )
 6484:     \ disassemble instruction w at addr
 6485:     2@@ >r ( addr w disasm-xt R: c-addr )
 6486:     execute ( R: c-addr ) \ disassemble operands
 6487:     r> count type ; \ print name 
 6488: @end example
 6489: 
 6490: Note that the tables here (in contrast to above) do the @code{cells +}
 6491: by themselves (that's why you have to pass an xt).  This word is used in
 6492: the following way:
 6493: 
 6494: @example
 6495: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6496: @end example
 6497: 
 6498: As shown above, the defined instruction format is then used like this:
 6499: 
 6500: @example
 6501: @var{entry-num} @var{inst-format} @var{inst-name}
 6502: @end example
 6503: 
 6504: In terms of currying, this kind of two-level defining word provides the
 6505: parameters in three stages: first @var{disasm-operands} and @var{table},
 6506: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6507: the instruction to be disassembled.  
 6508: 
 6509: Of course this did not quite fit all the instruction format names used
 6510: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6511: the parameters into the right form.
 6512: 
 6513: If you have trouble following this section, don't worry.  First, this is
 6514: involved and takes time (and probably some playing around) to
 6515: understand; second, this is the first two-level
 6516: @code{create}/@code{does>} word I have written in seventeen years of
 6517: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6518: have elected to use just a one-level defining word (with some repeating
 6519: of parameters when using the defining word). So it is not necessary to
 6520: understand this, but it may improve your understanding of Forth.
 6521: 
 6522: 
 6523: @node @code{Const-does>},  , Advanced does> usage example, User-defined Defining Words
 6524: @subsubsection @code{Const-does>}
 6525: 
 6526: A frequent use of @code{create}...@code{does>} is for transferring some
 6527: values from definition-time to run-time.  Gforth supports this use with
 6528: 
 6529: doc-const-does>
 6530: 
 6531: A typical use of this word is:
 6532: 
 6533: @example
 6534: : curry+ ( n1 "name" -- )
 6535: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6536:     + ;
 6537: 
 6538: 3 curry+ 3+
 6539: @end example
 6540: 
 6541: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6542: definition to run-time.
 6543: 
 6544: The advantages of using @code{const-does>} are:
 6545: 
 6546: @itemize
 6547: 
 6548: @item
 6549: You don't have to deal with storing and retrieving the values, i.e.,
 6550: your program becomes more writable and readable.
 6551: 
 6552: @item
 6553: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6554: be optimized away (because you could change the data using
 6555: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6556: 
 6557: @end itemize
 6558: 
 6559: An ANS Forth implementation of @code{const-does>} is available in
 6560: @file{compat/const-does.fs}.
 6561: 
 6562: 
 6563: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
 6564: @subsection Deferred words
 6565: @cindex deferred words
 6566: 
 6567: The defining word @code{Defer} allows you to define a word by name
 6568: without defining its behaviour; the definition of its behaviour is
 6569: deferred. Here are two situation where this can be useful:
 6570: 
 6571: @itemize @bullet
 6572: @item
 6573: Where you want to allow the behaviour of a word to be altered later, and
 6574: for all precompiled references to the word to change when its behaviour
 6575: is changed.
 6576: @item
 6577: For mutual recursion; @xref{Calls and returns}.
 6578: @end itemize
 6579: 
 6580: In the following example, @code{foo} always invokes the version of
 6581: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6582: always invokes the version that prints ``@code{Hello}''. There is no way
 6583: of getting @code{foo} to use the later version without re-ordering the
 6584: source code and recompiling it.
 6585: 
 6586: @example
 6587: : greet ." Good morning" ;
 6588: : foo ... greet ... ;
 6589: : greet ." Hello" ;
 6590: : bar ... greet ... ;
 6591: @end example
 6592: 
 6593: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6594: word. The behaviour of a @code{Defer}red word can be defined and
 6595: redefined at any time by using @code{IS} to associate the xt of a
 6596: previously-defined word with it. The previous example becomes:
 6597: 
 6598: @example
 6599: Defer greet ( -- )
 6600: : foo ... greet ... ;
 6601: : bar ... greet ... ;
 6602: : greet1 ( -- ) ." Good morning" ;
 6603: : greet2 ( -- ) ." Hello" ;
 6604: ' greet2 <IS> greet  \ make greet behave like greet2
 6605: @end example
 6606: 
 6607: @progstyle
 6608: You should write a stack comment for every deferred word, and put only
 6609: XTs into deferred words that conform to this stack effect.  Otherwise
 6610: it's too difficult to use the deferred word.
 6611: 
 6612: A deferred word can be used to improve the statistics-gathering example
 6613: from @ref{User-defined Defining Words}; rather than edit the
 6614: application's source code to change every @code{:} to a @code{my:}, do
 6615: this:
 6616: 
 6617: @example
 6618: : real: : ;     \ retain access to the original
 6619: defer :         \ redefine as a deferred word
 6620: ' my: <IS> :      \ use special version of :
 6621: \
 6622: \ load application here
 6623: \
 6624: ' real: <IS> :    \ go back to the original
 6625: @end example
 6626: 
 6627: 
 6628: One thing to note is that @code{<IS>} consumes its name when it is
 6629: executed.  If you want to specify the name at compile time, use
 6630: @code{[IS]}:
 6631: 
 6632: @example
 6633: : set-greet ( xt -- )
 6634:   [IS] greet ;
 6635: 
 6636: ' greet1 set-greet
 6637: @end example
 6638: 
 6639: A deferred word can only inherit execution semantics from the xt
 6640: (because that is all that an xt can represent -- for more discussion of
 6641: this @pxref{Tokens for Words}); by default it will have default
 6642: interpretation and compilation semantics deriving from this execution
 6643: semantics.  However, you can change the interpretation and compilation
 6644: semantics of the deferred word in the usual ways:
 6645: 
 6646: @example
 6647: : bar .... ; compile-only
 6648: Defer fred immediate
 6649: Defer jim
 6650: 
 6651: ' bar <IS> jim  \ jim has default semantics
 6652: ' bar <IS> fred \ fred is immediate
 6653: @end example
 6654: 
 6655: doc-defer
 6656: doc-<is>
 6657: doc-[is]
 6658: doc-is
 6659: @comment TODO document these: what's defers [is]
 6660: doc-what's
 6661: doc-defers
 6662: 
 6663: @c Use @code{words-deferred} to see a list of deferred words.
 6664: 
 6665: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
 6666: are provided in @file{compat/defer.fs}.
 6667: 
 6668: 
 6669: @node Aliases,  , Deferred words, Defining Words
 6670: @subsection Aliases
 6671: @cindex aliases
 6672: 
 6673: The defining word @code{Alias} allows you to define a word by name that
 6674: has the same behaviour as some other word. Here are two situation where
 6675: this can be useful:
 6676: 
 6677: @itemize @bullet
 6678: @item
 6679: When you want access to a word's definition from a different word list
 6680: (for an example of this, see the definition of the @code{Root} word list
 6681: in the Gforth source).
 6682: @item
 6683: When you want to create a synonym; a definition that can be known by
 6684: either of two names (for example, @code{THEN} and @code{ENDIF} are
 6685: aliases).
 6686: @end itemize
 6687: 
 6688: Like deferred words, an alias has default compilation and interpretation
 6689: semantics at the beginning (not the modifications of the other word),
 6690: but you can change them in the usual ways (@code{immediate},
 6691: @code{compile-only}). For example:
 6692: 
 6693: @example
 6694: : foo ... ; immediate
 6695: 
 6696: ' foo Alias bar \ bar is not an immediate word
 6697: ' foo Alias fooby immediate \ fooby is an immediate word
 6698: @end example
 6699: 
 6700: Words that are aliases have the same xt, different headers in the
 6701: dictionary, and consequently different name tokens (@pxref{Tokens for
 6702: Words}) and possibly different immediate flags.  An alias can only have
 6703: default or immediate compilation semantics; you can define aliases for
 6704: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 6705: 
 6706: doc-alias
 6707: 
 6708: 
 6709: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 6710: @section Interpretation and Compilation Semantics
 6711: @cindex semantics, interpretation and compilation
 6712: 
 6713: @c !! state and ' are used without explanation
 6714: @c example for immediate/compile-only? or is the tutorial enough
 6715: 
 6716: @cindex interpretation semantics
 6717: The @dfn{interpretation semantics} of a (named) word are what the text
 6718: interpreter does when it encounters the word in interpret state. It also
 6719: appears in some other contexts, e.g., the execution token returned by
 6720: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 6721: (in other words, @code{' @i{word} execute} is equivalent to
 6722: interpret-state text interpretation of @code{@i{word}}).
 6723: 
 6724: @cindex compilation semantics
 6725: The @dfn{compilation semantics} of a (named) word are what the text
 6726: interpreter does when it encounters the word in compile state. It also
 6727: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 6728: compiles@footnote{In standard terminology, ``appends to the current
 6729: definition''.} the compilation semantics of @i{word}.
 6730: 
 6731: @cindex execution semantics
 6732: The standard also talks about @dfn{execution semantics}. They are used
 6733: only for defining the interpretation and compilation semantics of many
 6734: words. By default, the interpretation semantics of a word are to
 6735: @code{execute} its execution semantics, and the compilation semantics of
 6736: a word are to @code{compile,} its execution semantics.@footnote{In
 6737: standard terminology: The default interpretation semantics are its
 6738: execution semantics; the default compilation semantics are to append its
 6739: execution semantics to the execution semantics of the current
 6740: definition.}
 6741: 
 6742: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 6743: the text interpreter, ticked, or @code{postpone}d, so they have no
 6744: interpretation or compilation semantics.  Their behaviour is represented
 6745: by their XT (@pxref{Tokens for Words}), and we call it execution
 6746: semantics, too.
 6747: 
 6748: @comment TODO expand, make it co-operate with new sections on text interpreter.
 6749: 
 6750: @cindex immediate words
 6751: @cindex compile-only words
 6752: You can change the semantics of the most-recently defined word:
 6753: 
 6754: 
 6755: doc-immediate
 6756: doc-compile-only
 6757: doc-restrict
 6758: 
 6759: By convention, words with non-default compilation semantics (e.g.,
 6760: immediate words) often have names surrounded with brackets (e.g.,
 6761: @code{[']}, @pxref{Execution token}).
 6762: 
 6763: Note that ticking (@code{'}) a compile-only word gives an error
 6764: (``Interpreting a compile-only word'').
 6765: 
 6766: @menu
 6767: * Combined words::              
 6768: @end menu
 6769: 
 6770: 
 6771: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 6772: @subsection Combined Words
 6773: @cindex combined words
 6774: 
 6775: Gforth allows you to define @dfn{combined words} -- words that have an
 6776: arbitrary combination of interpretation and compilation semantics.
 6777: 
 6778: doc-interpret/compile:
 6779: 
 6780: This feature was introduced for implementing @code{TO} and @code{S"}. I
 6781: recommend that you do not define such words, as cute as they may be:
 6782: they make it hard to get at both parts of the word in some contexts.
 6783: E.g., assume you want to get an execution token for the compilation
 6784: part. Instead, define two words, one that embodies the interpretation
 6785: part, and one that embodies the compilation part.  Once you have done
 6786: that, you can define a combined word with @code{interpret/compile:} for
 6787: the convenience of your users.
 6788: 
 6789: You might try to use this feature to provide an optimizing
 6790: implementation of the default compilation semantics of a word. For
 6791: example, by defining:
 6792: @example
 6793: :noname
 6794:    foo bar ;
 6795: :noname
 6796:    POSTPONE foo POSTPONE bar ;
 6797: interpret/compile: opti-foobar
 6798: @end example
 6799: 
 6800: @noindent
 6801: as an optimizing version of:
 6802: 
 6803: @example
 6804: : foobar
 6805:     foo bar ;
 6806: @end example
 6807: 
 6808: Unfortunately, this does not work correctly with @code{[compile]},
 6809: because @code{[compile]} assumes that the compilation semantics of all
 6810: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 6811: opti-foobar} would compile compilation semantics, whereas
 6812: @code{[compile] foobar} would compile interpretation semantics.
 6813: 
 6814: @cindex state-smart words (are a bad idea)
 6815: @anchor{state-smartness}
 6816: Some people try to use @dfn{state-smart} words to emulate the feature provided
 6817: by @code{interpret/compile:} (words are state-smart if they check
 6818: @code{STATE} during execution). E.g., they would try to code
 6819: @code{foobar} like this:
 6820: 
 6821: @example
 6822: : foobar
 6823:   STATE @@
 6824:   IF ( compilation state )
 6825:     POSTPONE foo POSTPONE bar
 6826:   ELSE
 6827:     foo bar
 6828:   ENDIF ; immediate
 6829: @end example
 6830: 
 6831: Although this works if @code{foobar} is only processed by the text
 6832: interpreter, it does not work in other contexts (like @code{'} or
 6833: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 6834: for a state-smart word, not for the interpretation semantics of the
 6835: original @code{foobar}; when you execute this execution token (directly
 6836: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 6837: state, the result will not be what you expected (i.e., it will not
 6838: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 6839: write them@footnote{For a more detailed discussion of this topic, see
 6840: M. Anton Ertl,
 6841: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 6842: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 6843: 
 6844: @cindex defining words with arbitrary semantics combinations
 6845: It is also possible to write defining words that define words with
 6846: arbitrary combinations of interpretation and compilation semantics. In
 6847: general, they look like this:
 6848: 
 6849: @example
 6850: : def-word
 6851:     create-interpret/compile
 6852:     @i{code1}
 6853: interpretation>
 6854:     @i{code2}
 6855: <interpretation
 6856: compilation>
 6857:     @i{code3}
 6858: <compilation ;
 6859: @end example
 6860: 
 6861: For a @i{word} defined with @code{def-word}, the interpretation
 6862: semantics are to push the address of the body of @i{word} and perform
 6863: @i{code2}, and the compilation semantics are to push the address of
 6864: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 6865: can also be defined like this (except that the defined constants don't
 6866: behave correctly when @code{[compile]}d):
 6867: 
 6868: @example
 6869: : constant ( n "name" -- )
 6870:     create-interpret/compile
 6871:     ,
 6872: interpretation> ( -- n )
 6873:     @@
 6874: <interpretation
 6875: compilation> ( compilation. -- ; run-time. -- n )
 6876:     @@ postpone literal
 6877: <compilation ;
 6878: @end example
 6879: 
 6880: 
 6881: doc-create-interpret/compile
 6882: doc-interpretation>
 6883: doc-<interpretation
 6884: doc-compilation>
 6885: doc-<compilation
 6886: 
 6887: 
 6888: Words defined with @code{interpret/compile:} and
 6889: @code{create-interpret/compile} have an extended header structure that
 6890: differs from other words; however, unless you try to access them with
 6891: plain address arithmetic, you should not notice this. Words for
 6892: accessing the header structure usually know how to deal with this; e.g.,
 6893: @code{'} @i{word} @code{>body} also gives you the body of a word created
 6894: with @code{create-interpret/compile}.
 6895: 
 6896: 
 6897: @c -------------------------------------------------------------
 6898: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 6899: @section Tokens for Words
 6900: @cindex tokens for words
 6901: 
 6902: This section describes the creation and use of tokens that represent
 6903: words.
 6904: 
 6905: @menu
 6906: * Execution token::             represents execution/interpretation semantics
 6907: * Compilation token::           represents compilation semantics
 6908: * Name token::                  represents named words
 6909: @end menu
 6910: 
 6911: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 6912: @subsection Execution token
 6913: 
 6914: @cindex xt
 6915: @cindex execution token
 6916: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 6917: You can use @code{execute} to invoke this behaviour.
 6918: 
 6919: @cindex tick (')
 6920: You can use @code{'} to get an execution token that represents the
 6921: interpretation semantics of a named word:
 6922: 
 6923: @example
 6924: 5 ' .   ( n xt ) 
 6925: execute ( )      \ execute the xt (i.e., ".")
 6926: @end example
 6927: 
 6928: doc-'
 6929: 
 6930: @code{'} parses at run-time; there is also a word @code{[']} that parses
 6931: when it is compiled, and compiles the resulting XT:
 6932: 
 6933: @example
 6934: : foo ['] . execute ;
 6935: 5 foo
 6936: : bar ' execute ; \ by contrast,
 6937: 5 bar .           \ ' parses "." when bar executes
 6938: @end example
 6939: 
 6940: doc-[']
 6941: 
 6942: If you want the execution token of @i{word}, write @code{['] @i{word}}
 6943: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 6944: @code{'} and @code{[']} behave somewhat unusually by complaining about
 6945: compile-only words (because these words have no interpretation
 6946: semantics).  You might get what you want by using @code{COMP' @i{word}
 6947: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 6948: token}).
 6949: 
 6950: Another way to get an XT is @code{:noname} or @code{latestxt}
 6951: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 6952: for the only behaviour the word has (the execution semantics).  For
 6953: named words, @code{latestxt} produces an XT for the same behaviour it
 6954: would produce if the word was defined anonymously.
 6955: 
 6956: @example
 6957: :noname ." hello" ;
 6958: execute
 6959: @end example
 6960: 
 6961: An XT occupies one cell and can be manipulated like any other cell.
 6962: 
 6963: @cindex code field address
 6964: @cindex CFA
 6965: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 6966: operations that produce or consume it).  For old hands: In Gforth, the
 6967: XT is implemented as a code field address (CFA).
 6968: 
 6969: doc-execute
 6970: doc-perform
 6971: 
 6972: @node Compilation token, Name token, Execution token, Tokens for Words
 6973: @subsection Compilation token
 6974: 
 6975: @cindex compilation token
 6976: @cindex CT (compilation token)
 6977: Gforth represents the compilation semantics of a named word by a
 6978: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 6979: @i{xt} is an execution token. The compilation semantics represented by
 6980: the compilation token can be performed with @code{execute}, which
 6981: consumes the whole compilation token, with an additional stack effect
 6982: determined by the represented compilation semantics.
 6983: 
 6984: At present, the @i{w} part of a compilation token is an execution token,
 6985: and the @i{xt} part represents either @code{execute} or
 6986: @code{compile,}@footnote{Depending upon the compilation semantics of the
 6987: word. If the word has default compilation semantics, the @i{xt} will
 6988: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 6989: @i{xt} will represent @code{execute}.}. However, don't rely on that
 6990: knowledge, unless necessary; future versions of Gforth may introduce
 6991: unusual compilation tokens (e.g., a compilation token that represents
 6992: the compilation semantics of a literal).
 6993: 
 6994: You can perform the compilation semantics represented by the compilation
 6995: token with @code{execute}.  You can compile the compilation semantics
 6996: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 6997: equivalent to @code{postpone @i{word}}.
 6998: 
 6999: doc-[comp']
 7000: doc-comp'
 7001: doc-postpone,
 7002: 
 7003: @node Name token,  , Compilation token, Tokens for Words
 7004: @subsection Name token
 7005: 
 7006: @cindex name token
 7007: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7008: token is an abstract data type that occurs as argument or result of the
 7009: words below.
 7010: 
 7011: @c !! put this elswhere?
 7012: @cindex name field address
 7013: @cindex NFA
 7014: The closest thing to the nt in older Forth systems is the name field
 7015: address (NFA), but there are significant differences: in older Forth
 7016: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7017: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7018: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7019: is a link field in the structure identified by the name token, but
 7020: searching usually uses a hash table external to these structures; the
 7021: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7022: implemented as the address of that count field.
 7023: 
 7024: doc-find-name
 7025: doc-latest
 7026: doc->name
 7027: doc-name>int
 7028: doc-name?int
 7029: doc-name>comp
 7030: doc-name>string
 7031: doc-id.
 7032: doc-.name
 7033: doc-.id
 7034: 
 7035: @c ----------------------------------------------------------
 7036: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7037: @section Compiling words
 7038: @cindex compiling words
 7039: @cindex macros
 7040: 
 7041: In contrast to most other languages, Forth has no strict boundary
 7042: between compilation and run-time.  E.g., you can run arbitrary code
 7043: between defining words (or for computing data used by defining words
 7044: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7045: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7046: running arbitrary code while compiling a colon definition (exception:
 7047: you must not allot dictionary space).
 7048: 
 7049: @menu
 7050: * Literals::                    Compiling data values
 7051: * Macros::                      Compiling words
 7052: @end menu
 7053: 
 7054: @node Literals, Macros, Compiling words, Compiling words
 7055: @subsection Literals
 7056: @cindex Literals
 7057: 
 7058: The simplest and most frequent example is to compute a literal during
 7059: compilation.  E.g., the following definition prints an array of strings,
 7060: one string per line:
 7061: 
 7062: @example
 7063: : .strings ( addr u -- ) \ gforth
 7064:     2* cells bounds U+DO
 7065: 	cr i 2@@ type
 7066:     2 cells +LOOP ;  
 7067: @end example
 7068: 
 7069: With a simple-minded compiler like Gforth's, this computes @code{2
 7070: cells} on every loop iteration.  You can compute this value once and for
 7071: all at compile time and compile it into the definition like this:
 7072: 
 7073: @example
 7074: : .strings ( addr u -- ) \ gforth
 7075:     2* cells bounds U+DO
 7076: 	cr i 2@@ type
 7077:     [ 2 cells ] literal +LOOP ;  
 7078: @end example
 7079: 
 7080: @code{[} switches the text interpreter to interpret state (you will get
 7081: an @code{ok} prompt if you type this example interactively and insert a
 7082: newline between @code{[} and @code{]}), so it performs the
 7083: interpretation semantics of @code{2 cells}; this computes a number.
 7084: @code{]} switches the text interpreter back into compile state.  It then
 7085: performs @code{Literal}'s compilation semantics, which are to compile
 7086: this number into the current word.  You can decompile the word with
 7087: @code{see .strings} to see the effect on the compiled code.
 7088: 
 7089: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7090: *} in this way.
 7091: 
 7092: doc-[
 7093: doc-]
 7094: doc-literal
 7095: doc-]L
 7096: 
 7097: There are also words for compiling other data types than single cells as
 7098: literals:
 7099: 
 7100: doc-2literal
 7101: doc-fliteral
 7102: doc-sliteral
 7103: 
 7104: @cindex colon-sys, passing data across @code{:}
 7105: @cindex @code{:}, passing data across
 7106: You might be tempted to pass data from outside a colon definition to the
 7107: inside on the data stack.  This does not work, because @code{:} puhes a
 7108: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7109: 
 7110: @example
 7111: 5 : foo literal ; \ error: "unstructured"
 7112: @end example
 7113: 
 7114: Instead, you have to pass the value in some other way, e.g., through a
 7115: variable:
 7116: 
 7117: @example
 7118: variable temp
 7119: 5 temp !
 7120: : foo [ temp @@ ] literal ;
 7121: @end example
 7122: 
 7123: 
 7124: @node Macros,  , Literals, Compiling words
 7125: @subsection Macros
 7126: @cindex Macros
 7127: @cindex compiling compilation semantics
 7128: 
 7129: @code{Literal} and friends compile data values into the current
 7130: definition.  You can also write words that compile other words into the
 7131: current definition.  E.g.,
 7132: 
 7133: @example
 7134: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7135:   POSTPONE + ;
 7136: 
 7137: : foo ( n1 n2 -- n )
 7138:   [ compile-+ ] ;
 7139: 1 2 foo .
 7140: @end example
 7141: 
 7142: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7143: What happens in this example?  @code{Postpone} compiles the compilation
 7144: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7145: executes @code{compile-+} and thus the compilation semantics of +, which
 7146: compile (the execution semantics of) @code{+} into
 7147: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7148: should only be executed in compile state, so this example is not
 7149: guaranteed to work on all standard systems, but on any decent system it
 7150: will work.}
 7151: 
 7152: doc-postpone
 7153: doc-[compile]
 7154: 
 7155: Compiling words like @code{compile-+} are usually immediate (or similar)
 7156: so you do not have to switch to interpret state to execute them;
 7157: mopifying the last example accordingly produces:
 7158: 
 7159: @example
 7160: : [compile-+] ( compilation: --; interpretation: -- )
 7161:   \ compiled code: ( n1 n2 -- n )
 7162:   POSTPONE + ; immediate
 7163: 
 7164: : foo ( n1 n2 -- n )
 7165:   [compile-+] ;
 7166: 1 2 foo .
 7167: @end example
 7168: 
 7169: Immediate compiling words are similar to macros in other languages (in
 7170: particular, Lisp).  The important differences to macros in, e.g., C are:
 7171: 
 7172: @itemize @bullet
 7173: 
 7174: @item
 7175: You use the same language for defining and processing macros, not a
 7176: separate preprocessing language and processor.
 7177: 
 7178: @item
 7179: Consequently, the full power of Forth is available in macro definitions.
 7180: E.g., you can perform arbitrarily complex computations, or generate
 7181: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7182: Tutorial}).  This power is very useful when writing a parser generators
 7183: or other code-generating software.
 7184: 
 7185: @item
 7186: Macros defined using @code{postpone} etc. deal with the language at a
 7187: higher level than strings; name binding happens at macro definition
 7188: time, so you can avoid the pitfalls of name collisions that can happen
 7189: in C macros.  Of course, Forth is a liberal language and also allows to
 7190: shoot yourself in the foot with text-interpreted macros like
 7191: 
 7192: @example
 7193: : [compile-+] s" +" evaluate ; immediate
 7194: @end example
 7195: 
 7196: Apart from binding the name at macro use time, using @code{evaluate}
 7197: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7198: @end itemize
 7199: 
 7200: You may want the macro to compile a number into a word.  The word to do
 7201: it is @code{literal}, but you have to @code{postpone} it, so its
 7202: compilation semantics take effect when the macro is executed, not when
 7203: it is compiled:
 7204: 
 7205: @example
 7206: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7207:   5 POSTPONE literal ; immediate
 7208: 
 7209: : foo [compile-5] ;
 7210: foo .
 7211: @end example
 7212: 
 7213: You may want to pass parameters to a macro, that the macro should
 7214: compile into the current definition.  If the parameter is a number, then
 7215: you can use @code{postpone literal} (similar for other values).
 7216: 
 7217: If you want to pass a word that is to be compiled, the usual way is to
 7218: pass an execution token and @code{compile,} it:
 7219: 
 7220: @example
 7221: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7222:   dup compile, compile, ;
 7223: 
 7224: : 2+ ( n1 -- n2 )
 7225:   [ ' 1+ twice1 ] ;
 7226: @end example
 7227: 
 7228: doc-compile,
 7229: 
 7230: An alternative available in Gforth, that allows you to pass compile-only
 7231: words as parameters is to use the compilation token (@pxref{Compilation
 7232: token}).  The same example in this technique:
 7233: 
 7234: @example
 7235: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7236:   2dup 2>r execute 2r> execute ;
 7237: 
 7238: : 2+ ( n1 -- n2 )
 7239:   [ comp' 1+ twice ] ;
 7240: @end example
 7241: 
 7242: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7243: works even if the executed compilation semantics has an effect on the
 7244: data stack.
 7245: 
 7246: You can also define complete definitions with these words; this provides
 7247: an alternative to using @code{does>} (@pxref{User-defined Defining
 7248: Words}).  E.g., instead of
 7249: 
 7250: @example
 7251: : curry+ ( n1 "name" -- )
 7252:     CREATE ,
 7253: DOES> ( n2 -- n1+n2 )
 7254:     @@ + ;
 7255: @end example
 7256: 
 7257: you could define
 7258: 
 7259: @example
 7260: : curry+ ( n1 "name" -- )
 7261:   \ name execution: ( n2 -- n1+n2 )
 7262:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7263: 
 7264: -3 curry+ 3-
 7265: see 3-
 7266: @end example
 7267: 
 7268: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7269: colon-sys on the data stack that makes everything below it unaccessible.
 7270: 
 7271: This way of writing defining words is sometimes more, sometimes less
 7272: convenient than using @code{does>} (@pxref{Advanced does> usage
 7273: example}).  One advantage of this method is that it can be optimized
 7274: better, because the compiler knows that the value compiled with
 7275: @code{literal} is fixed, whereas the data associated with a
 7276: @code{create}d word can be changed.
 7277: 
 7278: @c ----------------------------------------------------------
 7279: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7280: @section  The Text Interpreter
 7281: @cindex interpreter - outer
 7282: @cindex text interpreter
 7283: @cindex outer interpreter
 7284: 
 7285: @c Should we really describe all these ugly details?  IMO the text
 7286: @c interpreter should be much cleaner, but that may not be possible within
 7287: @c ANS Forth. - anton
 7288: @c nac-> I wanted to explain how it works to show how you can exploit
 7289: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7290: @c some of these gory details was very helpful to me. None of the textbooks
 7291: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7292: @c seems to positively avoid going into too much detail for some of
 7293: @c the internals.
 7294: 
 7295: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7296: @c it is; for the ugly details, I would prefer another place.  I wonder
 7297: @c whether we should have a chapter before "Words" that describes some
 7298: @c basic concepts referred to in words, and a chapter after "Words" that
 7299: @c describes implementation details.
 7300: 
 7301: The text interpreter@footnote{This is an expanded version of the
 7302: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7303: that processes input from the current input device. It is also called
 7304: the outer interpreter, in contrast to the inner interpreter
 7305: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7306: implementations.
 7307: 
 7308: @cindex interpret state
 7309: @cindex compile state
 7310: The text interpreter operates in one of two states: @dfn{interpret
 7311: state} and @dfn{compile state}. The current state is defined by the
 7312: aptly-named variable @code{state}.
 7313: 
 7314: This section starts by describing how the text interpreter behaves when
 7315: it is in interpret state, processing input from the user input device --
 7316: the keyboard. This is the mode that a Forth system is in after it starts
 7317: up.
 7318: 
 7319: @cindex input buffer
 7320: @cindex terminal input buffer
 7321: The text interpreter works from an area of memory called the @dfn{input
 7322: buffer}@footnote{When the text interpreter is processing input from the
 7323: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7324: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7325: @code{#TIB}.}, which stores your keyboard input when you press the
 7326: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7327: leading spaces (called @dfn{delimiters}) then parses a string (a
 7328: sequence of non-space characters) until it reaches either a space
 7329: character or the end of the buffer. Having parsed a string, it makes two
 7330: attempts to process it:
 7331: 
 7332: @cindex dictionary
 7333: @itemize @bullet
 7334: @item
 7335: It looks for the string in a @dfn{dictionary} of definitions. If the
 7336: string is found, the string names a @dfn{definition} (also known as a
 7337: @dfn{word}) and the dictionary search returns information that allows
 7338: the text interpreter to perform the word's @dfn{interpretation
 7339: semantics}. In most cases, this simply means that the word will be
 7340: executed.
 7341: @item
 7342: If the string is not found in the dictionary, the text interpreter
 7343: attempts to treat it as a number, using the rules described in
 7344: @ref{Number Conversion}. If the string represents a legal number in the
 7345: current radix, the number is pushed onto a parameter stack (the data
 7346: stack for integers, the floating-point stack for floating-point
 7347: numbers).
 7348: @end itemize
 7349: 
 7350: If both attempts fail, or if the word is found in the dictionary but has
 7351: no interpretation semantics@footnote{This happens if the word was
 7352: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7353: remainder of the input buffer, issues an error message and waits for
 7354: more input. If one of the attempts succeeds, the text interpreter
 7355: repeats the parsing process until the whole of the input buffer has been
 7356: processed, at which point it prints the status message ``@code{ ok}''
 7357: and waits for more input.
 7358: 
 7359: @c anton: this should be in the input stream subsection (or below it)
 7360: 
 7361: @cindex parse area
 7362: The text interpreter keeps track of its position in the input buffer by
 7363: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7364: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7365: of the input buffer. The region from offset @code{>IN @@} to the end of
 7366: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7367: the text interpreter processes the contents of the input buffer by
 7368: parsing strings from the parse area until the parse area is empty.}.
 7369: This example shows how @code{>IN} changes as the text interpreter parses
 7370: the input buffer:
 7371: 
 7372: @example
 7373: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7374:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7375: 
 7376: 1 2 3 remaining + remaining . 
 7377: 
 7378: : foo 1 2 3 remaining SWAP remaining ;
 7379: @end example
 7380: 
 7381: @noindent
 7382: The result is:
 7383: 
 7384: @example
 7385: ->+ remaining .<-
 7386: ->.<-5  ok
 7387: 
 7388: ->SWAP remaining ;-<
 7389: ->;<-  ok
 7390: @end example
 7391: 
 7392: @cindex parsing words
 7393: The value of @code{>IN} can also be modified by a word in the input
 7394: buffer that is executed by the text interpreter.  This means that a word
 7395: can ``trick'' the text interpreter into either skipping a section of the
 7396: input buffer@footnote{This is how parsing words work.} or into parsing a
 7397: section twice. For example:
 7398: 
 7399: @example
 7400: : lat ." <<foo>>" ;
 7401: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7402: @end example
 7403: 
 7404: @noindent
 7405: When @code{flat} is executed, this output is produced@footnote{Exercise
 7406: for the reader: what would happen if the @code{3} were replaced with
 7407: @code{4}?}:
 7408: 
 7409: @example
 7410: <<bar>><<foo>>
 7411: @end example
 7412: 
 7413: This technique can be used to work around some of the interoperability
 7414: problems of parsing words.  Of course, it's better to avoid parsing
 7415: words where possible.
 7416: 
 7417: @noindent
 7418: Two important notes about the behaviour of the text interpreter:
 7419: 
 7420: @itemize @bullet
 7421: @item
 7422: It processes each input string to completion before parsing additional
 7423: characters from the input buffer.
 7424: @item
 7425: It treats the input buffer as a read-only region (and so must your code).
 7426: @end itemize
 7427: 
 7428: @noindent
 7429: When the text interpreter is in compile state, its behaviour changes in
 7430: these ways:
 7431: 
 7432: @itemize @bullet
 7433: @item
 7434: If a parsed string is found in the dictionary, the text interpreter will
 7435: perform the word's @dfn{compilation semantics}. In most cases, this
 7436: simply means that the execution semantics of the word will be appended
 7437: to the current definition.
 7438: @item
 7439: When a number is encountered, it is compiled into the current definition
 7440: (as a literal) rather than being pushed onto a parameter stack.
 7441: @item
 7442: If an error occurs, @code{state} is modified to put the text interpreter
 7443: back into interpret state.
 7444: @item
 7445: Each time a line is entered from the keyboard, Gforth prints
 7446: ``@code{ compiled}'' rather than `` @code{ok}''.
 7447: @end itemize
 7448: 
 7449: @cindex text interpreter - input sources
 7450: When the text interpreter is using an input device other than the
 7451: keyboard, its behaviour changes in these ways:
 7452: 
 7453: @itemize @bullet
 7454: @item
 7455: When the parse area is empty, the text interpreter attempts to refill
 7456: the input buffer from the input source. When the input source is
 7457: exhausted, the input source is set back to the previous input source.
 7458: @item
 7459: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7460: time the parse area is emptied.
 7461: @item
 7462: If an error occurs, the input source is set back to the user input
 7463: device.
 7464: @end itemize
 7465: 
 7466: You can read about this in more detail in @ref{Input Sources}.
 7467: 
 7468: doc->in
 7469: doc-source
 7470: 
 7471: doc-tib
 7472: doc-#tib
 7473: 
 7474: 
 7475: @menu
 7476: * Input Sources::               
 7477: * Number Conversion::           
 7478: * Interpret/Compile states::    
 7479: * Interpreter Directives::      
 7480: @end menu
 7481: 
 7482: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7483: @subsection Input Sources
 7484: @cindex input sources
 7485: @cindex text interpreter - input sources
 7486: 
 7487: By default, the text interpreter processes input from the user input
 7488: device (the keyboard) when Forth starts up. The text interpreter can
 7489: process input from any of these sources:
 7490: 
 7491: @itemize @bullet
 7492: @item
 7493: The user input device -- the keyboard.
 7494: @item
 7495: A file, using the words described in @ref{Forth source files}.
 7496: @item
 7497: A block, using the words described in @ref{Blocks}.
 7498: @item
 7499: A text string, using @code{evaluate}.
 7500: @end itemize
 7501: 
 7502: A program can identify the current input device from the values of
 7503: @code{source-id} and @code{blk}.
 7504: 
 7505: 
 7506: doc-source-id
 7507: doc-blk
 7508: 
 7509: doc-save-input
 7510: doc-restore-input
 7511: 
 7512: doc-evaluate
 7513: doc-query
 7514: 
 7515: 
 7516: 
 7517: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7518: @subsection Number Conversion
 7519: @cindex number conversion
 7520: @cindex double-cell numbers, input format
 7521: @cindex input format for double-cell numbers
 7522: @cindex single-cell numbers, input format
 7523: @cindex input format for single-cell numbers
 7524: @cindex floating-point numbers, input format
 7525: @cindex input format for floating-point numbers
 7526: 
 7527: This section describes the rules that the text interpreter uses when it
 7528: tries to convert a string into a number.
 7529: 
 7530: Let <digit> represent any character that is a legal digit in the current
 7531: number base@footnote{For example, 0-9 when the number base is decimal or
 7532: 0-9, A-F when the number base is hexadecimal.}.
 7533: 
 7534: Let <decimal digit> represent any character in the range 0-9.
 7535: 
 7536: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7537: in the braces (@i{a} or @i{b} or neither).
 7538: 
 7539: Let * represent any number of instances of the previous character
 7540: (including none).
 7541: 
 7542: Let any other character represent itself.
 7543: 
 7544: @noindent
 7545: Now, the conversion rules are:
 7546: 
 7547: @itemize @bullet
 7548: @item
 7549: A string of the form <digit><digit>* is treated as a single-precision
 7550: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7551: @item
 7552: A string of the form -<digit><digit>* is treated as a single-precision
 7553: (cell-sized) negative integer, and is represented using 2's-complement
 7554: arithmetic. Examples are -45 -5681 -0
 7555: @item
 7556: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7557: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7558: (all three of these represent the same number).
 7559: @item
 7560: A string of the form -<digit><digit>*.<digit>* is treated as a
 7561: double-precision (double-cell-sized) negative integer, and is
 7562: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7563: -34.65 (all three of these represent the same number).
 7564: @item
 7565: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7566: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7567: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7568: number) +12.E-4
 7569: @end itemize
 7570: 
 7571: By default, the number base used for integer number conversion is given
 7572: by the contents of the variable @code{base}.  Note that a lot of
 7573: confusion can result from unexpected values of @code{base}.  If you
 7574: change @code{base} anywhere, make sure to save the old value and restore
 7575: it afterwards.  In general I recommend keeping @code{base} decimal, and
 7576: using the prefixes described below for the popular non-decimal bases.
 7577: 
 7578: doc-dpl
 7579: doc-base
 7580: doc-hex
 7581: doc-decimal
 7582: 
 7583: 
 7584: @cindex '-prefix for character strings
 7585: @cindex &-prefix for decimal numbers
 7586: @cindex %-prefix for binary numbers
 7587: @cindex $-prefix for hexadecimal numbers
 7588: Gforth allows you to override the value of @code{base} by using a
 7589: prefix@footnote{Some Forth implementations provide a similar scheme by
 7590: implementing @code{$} etc. as parsing words that process the subsequent
 7591: number in the input stream and push it onto the stack. For example, see
 7592: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7593: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7594: is required between the prefix and the number.} before the first digit
 7595: of an (integer) number. Four prefixes are supported:
 7596: 
 7597: @itemize @bullet
 7598: @item
 7599: @code{&} -- decimal
 7600: @item
 7601: @code{%} -- binary
 7602: @item
 7603: @code{$} -- hexadecimal
 7604: @item
 7605: @code{'} -- base @code{max-char+1}
 7606: @end itemize
 7607: 
 7608: Here are some examples, with the equivalent decimal number shown after
 7609: in braces:
 7610: 
 7611: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 7612: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
 7613: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
 7614: &905 (905), $abc (2478), $ABC (2478).
 7615: 
 7616: @cindex number conversion - traps for the unwary
 7617: @noindent
 7618: Number conversion has a number of traps for the unwary:
 7619: 
 7620: @itemize @bullet
 7621: @item
 7622: You cannot determine the current number base using the code sequence
 7623: @code{base @@ .} -- the number base is always 10 in the current number
 7624: base. Instead, use something like @code{base @@ dec.}
 7625: @item
 7626: If the number base is set to a value greater than 14 (for example,
 7627: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 7628: it to be intepreted as either a single-precision integer or a
 7629: floating-point number (Gforth treats it as an integer). The ambiguity
 7630: can be resolved by explicitly stating the sign of the mantissa and/or
 7631: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 7632: ambiguity arises; either representation will be treated as a
 7633: floating-point number.
 7634: @item
 7635: There is a word @code{bin} but it does @i{not} set the number base!
 7636: It is used to specify file types.
 7637: @item
 7638: ANS Forth requires the @code{.} of a double-precision number to be the
 7639: final character in the string.  Gforth allows the @code{.} to be
 7640: anywhere after the first digit.
 7641: @item
 7642: The number conversion process does not check for overflow.
 7643: @item
 7644: In an ANS Forth program @code{base} is required to be decimal when
 7645: converting floating-point numbers.  In Gforth, number conversion to
 7646: floating-point numbers always uses base &10, irrespective of the value
 7647: of @code{base}.
 7648: @end itemize
 7649: 
 7650: You can read numbers into your programs with the words described in
 7651: @ref{Input}.
 7652: 
 7653: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 7654: @subsection Interpret/Compile states
 7655: @cindex Interpret/Compile states
 7656: 
 7657: A standard program is not permitted to change @code{state}
 7658: explicitly. However, it can change @code{state} implicitly, using the
 7659: words @code{[} and @code{]}. When @code{[} is executed it switches
 7660: @code{state} to interpret state, and therefore the text interpreter
 7661: starts interpreting. When @code{]} is executed it switches @code{state}
 7662: to compile state and therefore the text interpreter starts
 7663: compiling. The most common usage for these words is for switching into
 7664: interpret state and back from within a colon definition; this technique
 7665: can be used to compile a literal (for an example, @pxref{Literals}) or
 7666: for conditional compilation (for an example, @pxref{Interpreter
 7667: Directives}).
 7668: 
 7669: 
 7670: @c This is a bad example: It's non-standard, and it's not necessary.
 7671: @c However, I can't think of a good example for switching into compile
 7672: @c state when there is no current word (@code{state}-smart words are not a
 7673: @c good reason).  So maybe we should use an example for switching into
 7674: @c interpret @code{state} in a colon def. - anton
 7675: @c nac-> I agree. I started out by putting in the example, then realised
 7676: @c that it was non-ANS, so wrote more words around it. I hope this
 7677: @c re-written version is acceptable to you. I do want to keep the example
 7678: @c as it is helpful for showing what is and what is not portable, particularly
 7679: @c where it outlaws a style in common use.
 7680: 
 7681: @c anton: it's more important to show what's portable.  After we have done
 7682: @c that, we can also show what's not.  In any case, I have written a
 7683: @c section Compiling Words which also deals with [ ].
 7684: 
 7685: @c  !! The following example does not work in Gforth 0.5.9 or later.
 7686: 
 7687: @c  @code{[} and @code{]} also give you the ability to switch into compile
 7688: @c  state and back, but we cannot think of any useful Standard application
 7689: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 7690: 
 7691: @c  @example
 7692: @c  : AA ." this is A" ;
 7693: @c  : BB ." this is B" ;
 7694: @c  : CC ." this is C" ;
 7695: 
 7696: @c  create table ] aa bb cc [
 7697: 
 7698: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 7699: @c    cells table + @@ execute ;
 7700: @c  @end example
 7701: 
 7702: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 7703: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 7704: @c  defining @code{table} like this:
 7705: 
 7706: @c  @example
 7707: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 7708: @c  @end example
 7709: 
 7710: @c  The problem with this code is that the definition of @code{table} is not
 7711: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 7712: @c  @i{may} work on systems where code space and data space co-incide, the
 7713: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 7714: @c  word. In addition, the Standard only allows @code{@@} to access data
 7715: @c  space, whilst this example is using it to access code space. The only
 7716: @c  portable, Standard way to build this table is to build it in data space,
 7717: @c  like this:
 7718: 
 7719: @c  @example
 7720: @c  create table ' aa , ' bb , ' cc ,
 7721: @c  @end example
 7722: 
 7723: @c  doc-state
 7724: 
 7725: 
 7726: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 7727: @subsection Interpreter Directives
 7728: @cindex interpreter directives
 7729: @cindex conditional compilation
 7730: 
 7731: These words are usually used in interpret state; typically to control
 7732: which parts of a source file are processed by the text
 7733: interpreter. There are only a few ANS Forth Standard words, but Gforth
 7734: supplements these with a rich set of immediate control structure words
 7735: to compensate for the fact that the non-immediate versions can only be
 7736: used in compile state (@pxref{Control Structures}). Typical usages:
 7737: 
 7738: @example
 7739: FALSE Constant HAVE-ASSEMBLER
 7740: .
 7741: .
 7742: HAVE-ASSEMBLER [IF]
 7743: : ASSEMBLER-FEATURE
 7744:   ...
 7745: ;
 7746: [ENDIF]
 7747: .
 7748: .
 7749: : SEE
 7750:   ... \ general-purpose SEE code
 7751:   [ HAVE-ASSEMBLER [IF] ]
 7752:   ... \ assembler-specific SEE code
 7753:   [ [ENDIF] ]
 7754: ;
 7755: @end example
 7756: 
 7757: 
 7758: doc-[IF]
 7759: doc-[ELSE]
 7760: doc-[THEN]
 7761: doc-[ENDIF]
 7762: 
 7763: doc-[IFDEF]
 7764: doc-[IFUNDEF]
 7765: 
 7766: doc-[?DO]
 7767: doc-[DO]
 7768: doc-[FOR]
 7769: doc-[LOOP]
 7770: doc-[+LOOP]
 7771: doc-[NEXT]
 7772: 
 7773: doc-[BEGIN]
 7774: doc-[UNTIL]
 7775: doc-[AGAIN]
 7776: doc-[WHILE]
 7777: doc-[REPEAT]
 7778: 
 7779: 
 7780: @c -------------------------------------------------------------
 7781: @node The Input Stream, Word Lists, The Text Interpreter, Words
 7782: @section The Input Stream
 7783: @cindex input stream
 7784: 
 7785: @c !! integrate this better with the "Text Interpreter" section
 7786: The text interpreter reads from the input stream, which can come from
 7787: several sources (@pxref{Input Sources}).  Some words, in particular
 7788: defining words, but also words like @code{'}, read parameters from the
 7789: input stream instead of from the stack.
 7790: 
 7791: Such words are called parsing words, because they parse the input
 7792: stream.  Parsing words are hard to use in other words, because it is
 7793: hard to pass program-generated parameters through the input stream.
 7794: They also usually have an unintuitive combination of interpretation and
 7795: compilation semantics when implemented naively, leading to various
 7796: approaches that try to produce a more intuitive behaviour
 7797: (@pxref{Combined words}).
 7798: 
 7799: It should be obvious by now that parsing words are a bad idea.  If you
 7800: want to implement a parsing word for convenience, also provide a factor
 7801: of the word that does not parse, but takes the parameters on the stack.
 7802: To implement the parsing word on top if it, you can use the following
 7803: words:
 7804: 
 7805: @c anton: these belong in the input stream section
 7806: doc-parse
 7807: doc-parse-word
 7808: doc-name
 7809: doc-word
 7810: doc-\"-parse
 7811: doc-refill
 7812: 
 7813: Conversely, if you have the bad luck (or lack of foresight) to have to
 7814: deal with parsing words without having such factors, how do you pass a
 7815: string that is not in the input stream to it?
 7816: 
 7817: doc-execute-parsing
 7818: 
 7819: If you want to run a parsing word on a file, the following word should
 7820: help:
 7821: 
 7822: doc-execute-parsing-file
 7823: 
 7824: @c -------------------------------------------------------------
 7825: @node Word Lists, Environmental Queries, The Input Stream, Words
 7826: @section Word Lists
 7827: @cindex word lists
 7828: @cindex header space
 7829: 
 7830: A wordlist is a list of named words; you can add new words and look up
 7831: words by name (and you can remove words in a restricted way with
 7832: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 7833: 
 7834: @cindex search order stack
 7835: The text interpreter searches the wordlists present in the search order
 7836: (a stack of wordlists), from the top to the bottom.  Within each
 7837: wordlist, the search starts conceptually at the newest word; i.e., if
 7838: two words in a wordlist have the same name, the newer word is found.
 7839: 
 7840: @cindex compilation word list
 7841: New words are added to the @dfn{compilation wordlist} (aka current
 7842: wordlist).
 7843: 
 7844: @cindex wid
 7845: A word list is identified by a cell-sized word list identifier (@i{wid})
 7846: in much the same way as a file is identified by a file handle. The
 7847: numerical value of the wid has no (portable) meaning, and might change
 7848: from session to session.
 7849: 
 7850: The ANS Forth ``Search order'' word set is intended to provide a set of
 7851: low-level tools that allow various different schemes to be
 7852: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 7853: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 7854: Forth.
 7855: 
 7856: @comment TODO: locals section refers to here, saying that every word list (aka
 7857: @comment vocabulary) has its own methods for searching etc. Need to document that.
 7858: @c anton: but better in a separate subsection on wordlist internals
 7859: 
 7860: @comment TODO: document markers, reveal, tables, mappedwordlist
 7861: 
 7862: @comment the gforthman- prefix is used to pick out the true definition of a
 7863: @comment word from the source files, rather than some alias.
 7864: 
 7865: doc-forth-wordlist
 7866: doc-definitions
 7867: doc-get-current
 7868: doc-set-current
 7869: doc-get-order
 7870: doc---gforthman-set-order
 7871: doc-wordlist
 7872: doc-table
 7873: doc->order
 7874: doc-previous
 7875: doc-also
 7876: doc---gforthman-forth
 7877: doc-only
 7878: doc---gforthman-order
 7879: 
 7880: doc-find
 7881: doc-search-wordlist
 7882: 
 7883: doc-words
 7884: doc-vlist
 7885: @c doc-words-deferred
 7886: 
 7887: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 7888: doc-root
 7889: doc-vocabulary
 7890: doc-seal
 7891: doc-vocs
 7892: doc-current
 7893: doc-context
 7894: 
 7895: 
 7896: @menu
 7897: * Vocabularies::                
 7898: * Why use word lists?::         
 7899: * Word list example::           
 7900: @end menu
 7901: 
 7902: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 7903: @subsection Vocabularies
 7904: @cindex Vocabularies, detailed explanation
 7905: 
 7906: Here is an example of creating and using a new wordlist using ANS
 7907: Forth words:
 7908: 
 7909: @example
 7910: wordlist constant my-new-words-wordlist
 7911: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 7912: 
 7913: \ add it to the search order
 7914: also my-new-words
 7915: 
 7916: \ alternatively, add it to the search order and make it
 7917: \ the compilation word list
 7918: also my-new-words definitions
 7919: \ type "order" to see the problem
 7920: @end example
 7921: 
 7922: The problem with this example is that @code{order} has no way to
 7923: associate the name @code{my-new-words} with the wid of the word list (in
 7924: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 7925: that has no associated name). There is no Standard way of associating a
 7926: name with a wid.
 7927: 
 7928: In Gforth, this example can be re-coded using @code{vocabulary}, which
 7929: associates a name with a wid:
 7930: 
 7931: @example
 7932: vocabulary my-new-words
 7933: 
 7934: \ add it to the search order
 7935: also my-new-words
 7936: 
 7937: \ alternatively, add it to the search order and make it
 7938: \ the compilation word list
 7939: my-new-words definitions
 7940: \ type "order" to see that the problem is solved
 7941: @end example
 7942: 
 7943: 
 7944: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 7945: @subsection Why use word lists?
 7946: @cindex word lists - why use them?
 7947: 
 7948: Here are some reasons why people use wordlists:
 7949: 
 7950: @itemize @bullet
 7951: 
 7952: @c anton: Gforth's hashing implementation makes the search speed
 7953: @c independent from the number of words.  But it is linear with the number
 7954: @c of wordlists that have to be searched, so in effect using more wordlists
 7955: @c actually slows down compilation.
 7956: 
 7957: @c @item
 7958: @c To improve compilation speed by reducing the number of header space
 7959: @c entries that must be searched. This is achieved by creating a new
 7960: @c word list that contains all of the definitions that are used in the
 7961: @c definition of a Forth system but which would not usually be used by
 7962: @c programs running on that system. That word list would be on the search
 7963: @c list when the Forth system was compiled but would be removed from the
 7964: @c search list for normal operation. This can be a useful technique for
 7965: @c low-performance systems (for example, 8-bit processors in embedded
 7966: @c systems) but is unlikely to be necessary in high-performance desktop
 7967: @c systems.
 7968: 
 7969: @item
 7970: To prevent a set of words from being used outside the context in which
 7971: they are valid. Two classic examples of this are an integrated editor
 7972: (all of the edit commands are defined in a separate word list; the
 7973: search order is set to the editor word list when the editor is invoked;
 7974: the old search order is restored when the editor is terminated) and an
 7975: integrated assembler (the op-codes for the machine are defined in a
 7976: separate word list which is used when a @code{CODE} word is defined).
 7977: 
 7978: @item
 7979: To organize the words of an application or library into a user-visible
 7980: set (in @code{forth-wordlist} or some other common wordlist) and a set
 7981: of helper words used just for the implementation (hidden in a separate
 7982: wordlist).  This keeps @code{words}' output smaller, separates
 7983: implementation and interface, and reduces the chance of name conflicts
 7984: within the common wordlist.
 7985: 
 7986: @item
 7987: To prevent a name-space clash between multiple definitions with the same
 7988: name. For example, when building a cross-compiler you might have a word
 7989: @code{IF} that generates conditional code for your target system. By
 7990: placing this definition in a different word list you can control whether
 7991: the host system's @code{IF} or the target system's @code{IF} get used in
 7992: any particular context by controlling the order of the word lists on the
 7993: search order stack.
 7994: 
 7995: @end itemize
 7996: 
 7997: The downsides of using wordlists are:
 7998: 
 7999: @itemize
 8000: 
 8001: @item
 8002: Debugging becomes more cumbersome.
 8003: 
 8004: @item
 8005: Name conflicts worked around with wordlists are still there, and you
 8006: have to arrange the search order carefully to get the desired results;
 8007: if you forget to do that, you get hard-to-find errors (as in any case
 8008: where you read the code differently from the compiler; @code{see} can
 8009: help seeing which of several possible words the name resolves to in such
 8010: cases).  @code{See} displays just the name of the words, not what
 8011: wordlist they belong to, so it might be misleading.  Using unique names
 8012: is a better approach to avoid name conflicts.
 8013: 
 8014: @item
 8015: You have to explicitly undo any changes to the search order.  In many
 8016: cases it would be more convenient if this happened implicitly.  Gforth
 8017: currently does not provide such a feature, but it may do so in the
 8018: future.
 8019: @end itemize
 8020: 
 8021: 
 8022: @node Word list example,  , Why use word lists?, Word Lists
 8023: @subsection Word list example
 8024: @cindex word lists - example
 8025: 
 8026: The following example is from the
 8027: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8028: garbage collector} and uses wordlists to separate public words from
 8029: helper words:
 8030: 
 8031: @example
 8032: get-current ( wid )
 8033: vocabulary garbage-collector also garbage-collector definitions
 8034: ... \ define helper words
 8035: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8036: ... \ define the public (i.e., API) words
 8037:     \ they can refer to the helper words
 8038: previous \ restore original search order (helper words become invisible)
 8039: @end example
 8040: 
 8041: @c -------------------------------------------------------------
 8042: @node Environmental Queries, Files, Word Lists, Words
 8043: @section Environmental Queries
 8044: @cindex environmental queries
 8045: 
 8046: ANS Forth introduced the idea of ``environmental queries'' as a way
 8047: for a program running on a system to determine certain characteristics of the system.
 8048: The Standard specifies a number of strings that might be recognised by a system.
 8049: 
 8050: The Standard requires that the header space used for environmental queries
 8051: be distinct from the header space used for definitions.
 8052: 
 8053: Typically, environmental queries are supported by creating a set of
 8054: definitions in a word list that is @i{only} used during environmental
 8055: queries; that is what Gforth does. There is no Standard way of adding
 8056: definitions to the set of recognised environmental queries, but any
 8057: implementation that supports the loading of optional word sets must have
 8058: some mechanism for doing this (after loading the word set, the
 8059: associated environmental query string must return @code{true}). In
 8060: Gforth, the word list used to honour environmental queries can be
 8061: manipulated just like any other word list.
 8062: 
 8063: 
 8064: doc-environment?
 8065: doc-environment-wordlist
 8066: 
 8067: doc-gforth
 8068: doc-os-class
 8069: 
 8070: 
 8071: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8072: returning two items on the stack, querying it using @code{environment?}
 8073: will return an additional item; the @code{true} flag that shows that the
 8074: string was recognised.
 8075: 
 8076: @comment TODO Document the standard strings or note where they are documented herein
 8077: 
 8078: Here are some examples of using environmental queries:
 8079: 
 8080: @example
 8081: s" address-unit-bits" environment? 0=
 8082: [IF]
 8083:      cr .( environmental attribute address-units-bits unknown... ) cr
 8084: [ELSE]
 8085:      drop \ ensure balanced stack effect
 8086: [THEN]
 8087: 
 8088: \ this might occur in the prelude of a standard program that uses THROW
 8089: s" exception" environment? [IF]
 8090:    0= [IF]
 8091:       : throw abort" exception thrown" ;
 8092:    [THEN]
 8093: [ELSE] \ we don't know, so make sure
 8094:    : throw abort" exception thrown" ;
 8095: [THEN]
 8096: 
 8097: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8098:                         [ELSE] .( Not Gforth..) [THEN]
 8099: 
 8100: \ a program using v*
 8101: s" gforth" environment? [IF]
 8102:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8103:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8104:      >r swap 2swap swap 0e r> 0 ?DO
 8105:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
 8106:      LOOP
 8107:      2drop 2drop ; 
 8108:   [THEN]
 8109: [ELSE] \ 
 8110:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8111:   ...
 8112: [THEN]
 8113: @end example
 8114: 
 8115: Here is an example of adding a definition to the environment word list:
 8116: 
 8117: @example
 8118: get-current environment-wordlist set-current
 8119: true constant block
 8120: true constant block-ext
 8121: set-current
 8122: @end example
 8123: 
 8124: You can see what definitions are in the environment word list like this:
 8125: 
 8126: @example
 8127: environment-wordlist >order words previous
 8128: @end example
 8129: 
 8130: 
 8131: @c -------------------------------------------------------------
 8132: @node Files, Blocks, Environmental Queries, Words
 8133: @section Files
 8134: @cindex files
 8135: @cindex I/O - file-handling
 8136: 
 8137: Gforth provides facilities for accessing files that are stored in the
 8138: host operating system's file-system. Files that are processed by Gforth
 8139: can be divided into two categories:
 8140: 
 8141: @itemize @bullet
 8142: @item
 8143: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8144: @item
 8145: Files that are processed by some other program (@dfn{general files}).
 8146: @end itemize
 8147: 
 8148: @menu
 8149: * Forth source files::          
 8150: * General files::               
 8151: * Search Paths::                
 8152: @end menu
 8153: 
 8154: @c -------------------------------------------------------------
 8155: @node Forth source files, General files, Files, Files
 8156: @subsection Forth source files
 8157: @cindex including files
 8158: @cindex Forth source files
 8159: 
 8160: The simplest way to interpret the contents of a file is to use one of
 8161: these two formats:
 8162: 
 8163: @example
 8164: include mysource.fs
 8165: s" mysource.fs" included
 8166: @end example
 8167: 
 8168: You usually want to include a file only if it is not included already
 8169: (by, say, another source file). In that case, you can use one of these
 8170: three formats:
 8171: 
 8172: @example
 8173: require mysource.fs
 8174: needs mysource.fs
 8175: s" mysource.fs" required
 8176: @end example
 8177: 
 8178: @cindex stack effect of included files
 8179: @cindex including files, stack effect
 8180: It is good practice to write your source files such that interpreting them
 8181: does not change the stack. Source files designed in this way can be used with
 8182: @code{required} and friends without complications. For example:
 8183: 
 8184: @example
 8185: 1024 require foo.fs drop
 8186: @end example
 8187: 
 8188: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8189: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8190: ), which allows its use with @code{require}.  Of course with such
 8191: parameters to required files, you have to ensure that the first
 8192: @code{require} fits for all uses (i.e., @code{require} it early in the
 8193: master load file).
 8194: 
 8195: doc-include-file
 8196: doc-included
 8197: doc-included?
 8198: doc-include
 8199: doc-required
 8200: doc-require
 8201: doc-needs
 8202: @c doc-init-included-files @c internal
 8203: doc-sourcefilename
 8204: doc-sourceline#
 8205: 
 8206: A definition in ANS Forth for @code{required} is provided in
 8207: @file{compat/required.fs}.
 8208: 
 8209: @c -------------------------------------------------------------
 8210: @node General files, Search Paths, Forth source files, Files
 8211: @subsection General files
 8212: @cindex general files
 8213: @cindex file-handling
 8214: 
 8215: Files are opened/created by name and type. The following file access
 8216: methods (FAMs) are recognised:
 8217: 
 8218: @cindex fam (file access method)
 8219: doc-r/o
 8220: doc-r/w
 8221: doc-w/o
 8222: doc-bin
 8223: 
 8224: 
 8225: When a file is opened/created, it returns a file identifier,
 8226: @i{wfileid} that is used for all other file commands. All file
 8227: commands also return a status value, @i{wior}, that is 0 for a
 8228: successful operation and an implementation-defined non-zero value in the
 8229: case of an error.
 8230: 
 8231: 
 8232: doc-open-file
 8233: doc-create-file
 8234: 
 8235: doc-close-file
 8236: doc-delete-file
 8237: doc-rename-file
 8238: doc-read-file
 8239: doc-read-line
 8240: doc-write-file
 8241: doc-write-line
 8242: doc-emit-file
 8243: doc-flush-file
 8244: 
 8245: doc-file-status
 8246: doc-file-position
 8247: doc-reposition-file
 8248: doc-file-size
 8249: doc-resize-file
 8250: 
 8251: doc-slurp-file
 8252: doc-slurp-fid
 8253: doc-stdin
 8254: doc-stdout
 8255: doc-stderr
 8256: 
 8257: @c ---------------------------------------------------------
 8258: @node Search Paths,  , General files, Files
 8259: @subsection Search Paths
 8260: @cindex path for @code{included}
 8261: @cindex file search path
 8262: @cindex @code{include} search path
 8263: @cindex search path for files
 8264: 
 8265: If you specify an absolute filename (i.e., a filename starting with
 8266: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8267: @samp{C:...})) for @code{included} and friends, that file is included
 8268: just as you would expect.
 8269: 
 8270: If the filename starts with @file{./}, this refers to the directory that
 8271: the present file was @code{included} from.  This allows files to include
 8272: other files relative to their own position (irrespective of the current
 8273: working directory or the absolute position).  This feature is essential
 8274: for libraries consisting of several files, where a file may include
 8275: other files from the library.  It corresponds to @code{#include "..."}
 8276: in C. If the current input source is not a file, @file{.} refers to the
 8277: directory of the innermost file being included, or, if there is no file
 8278: being included, to the current working directory.
 8279: 
 8280: For relative filenames (not starting with @file{./}), Gforth uses a
 8281: search path similar to Forth's search order (@pxref{Word Lists}). It
 8282: tries to find the given filename in the directories present in the path,
 8283: and includes the first one it finds. There are separate search paths for
 8284: Forth source files and general files.  If the search path contains the
 8285: directory @file{.}, this refers to the directory of the current file, or
 8286: the working directory, as if the file had been specified with @file{./}.
 8287: 
 8288: Use @file{~+} to refer to the current working directory (as in the
 8289: @code{bash}).
 8290: 
 8291: @c anton: fold the following subsubsections into this subsection?
 8292: 
 8293: @menu
 8294: * Source Search Paths::         
 8295: * General Search Paths::        
 8296: @end menu
 8297: 
 8298: @c ---------------------------------------------------------
 8299: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8300: @subsubsection Source Search Paths
 8301: @cindex search path control, source files
 8302: 
 8303: The search path is initialized when you start Gforth (@pxref{Invoking
 8304: Gforth}). You can display it and change it using @code{fpath} in
 8305: combination with the general path handling words.
 8306: 
 8307: doc-fpath
 8308: @c the functionality of the following words is easily available through
 8309: @c   fpath and the general path words.  The may go away.
 8310: @c doc-.fpath
 8311: @c doc-fpath+
 8312: @c doc-fpath=
 8313: @c doc-open-fpath-file
 8314: 
 8315: @noindent
 8316: Here is an example of using @code{fpath} and @code{require}:
 8317: 
 8318: @example
 8319: fpath path= /usr/lib/forth/|./
 8320: require timer.fs
 8321: @end example
 8322: 
 8323: 
 8324: @c ---------------------------------------------------------
 8325: @node General Search Paths,  , Source Search Paths, Search Paths
 8326: @subsubsection General Search Paths
 8327: @cindex search path control, source files
 8328: 
 8329: Your application may need to search files in several directories, like
 8330: @code{included} does. To facilitate this, Gforth allows you to define
 8331: and use your own search paths, by providing generic equivalents of the
 8332: Forth search path words:
 8333: 
 8334: doc-open-path-file
 8335: doc-path-allot
 8336: doc-clear-path
 8337: doc-also-path
 8338: doc-.path
 8339: doc-path+
 8340: doc-path=
 8341: 
 8342: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8343: 
 8344: Here's an example of creating an empty search path:
 8345: @c
 8346: @example
 8347: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8348: @end example
 8349: 
 8350: @c -------------------------------------------------------------
 8351: @node Blocks, Other I/O, Files, Words
 8352: @section Blocks
 8353: @cindex I/O - blocks
 8354: @cindex blocks
 8355: 
 8356: When you run Gforth on a modern desk-top computer, it runs under the
 8357: control of an operating system which provides certain services.  One of
 8358: these services is @var{file services}, which allows Forth source code
 8359: and data to be stored in files and read into Gforth (@pxref{Files}).
 8360: 
 8361: Traditionally, Forth has been an important programming language on
 8362: systems where it has interfaced directly to the underlying hardware with
 8363: no intervening operating system. Forth provides a mechanism, called
 8364: @dfn{blocks}, for accessing mass storage on such systems.
 8365: 
 8366: A block is a 1024-byte data area, which can be used to hold data or
 8367: Forth source code. No structure is imposed on the contents of the
 8368: block. A block is identified by its number; blocks are numbered
 8369: contiguously from 1 to an implementation-defined maximum.
 8370: 
 8371: A typical system that used blocks but no operating system might use a
 8372: single floppy-disk drive for mass storage, with the disks formatted to
 8373: provide 256-byte sectors. Blocks would be implemented by assigning the
 8374: first four sectors of the disk to block 1, the second four sectors to
 8375: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8376: would not contain any file system information, just the set of blocks.
 8377: 
 8378: @cindex blocks file
 8379: On systems that do provide file services, blocks are typically
 8380: implemented by storing a sequence of blocks within a single @dfn{blocks
 8381: file}.  The size of the blocks file will be an exact multiple of 1024
 8382: bytes, corresponding to the number of blocks it contains. This is the
 8383: mechanism that Gforth uses.
 8384: 
 8385: @cindex @file{blocks.fb}
 8386: Only one blocks file can be open at a time. If you use block words without
 8387: having specified a blocks file, Gforth defaults to the blocks file
 8388: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8389: locate a blocks file (@pxref{Source Search Paths}).
 8390: 
 8391: @cindex block buffers
 8392: When you read and write blocks under program control, Gforth uses a
 8393: number of @dfn{block buffers} as intermediate storage. These buffers are
 8394: not used when you use @code{load} to interpret the contents of a block.
 8395: 
 8396: The behaviour of the block buffers is analagous to that of a cache.
 8397: Each block buffer has three states:
 8398: 
 8399: @itemize @bullet
 8400: @item
 8401: Unassigned
 8402: @item
 8403: Assigned-clean
 8404: @item
 8405: Assigned-dirty
 8406: @end itemize
 8407: 
 8408: Initially, all block buffers are @i{unassigned}. In order to access a
 8409: block, the block (specified by its block number) must be assigned to a
 8410: block buffer.
 8411: 
 8412: The assignment of a block to a block buffer is performed by @code{block}
 8413: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8414: contents of a block. Use @code{buffer} when you don't care about the
 8415: existing contents of the block@footnote{The ANS Forth definition of
 8416: @code{buffer} is intended not to cause disk I/O; if the data associated
 8417: with the particular block is already stored in a block buffer due to an
 8418: earlier @code{block} command, @code{buffer} will return that block
 8419: buffer and the existing contents of the block will be
 8420: available. Otherwise, @code{buffer} will simply assign a new, empty
 8421: block buffer for the block.}.
 8422: 
 8423: Once a block has been assigned to a block buffer using @code{block} or
 8424: @code{buffer}, that block buffer becomes the @i{current block
 8425: buffer}. Data may only be manipulated (read or written) within the
 8426: current block buffer.
 8427: 
 8428: When the contents of the current block buffer has been modified it is
 8429: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8430: either abandon the changes (by doing nothing) or mark the block as
 8431: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8432: not change the blocks file; it simply changes a block buffer's state to
 8433: @i{assigned-dirty}.  The block will be written implicitly when it's
 8434: buffer is needed for another block, or explicitly by @code{flush} or
 8435: @code{save-buffers}.
 8436: 
 8437: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8438: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8439: @code{flush}.
 8440: 
 8441: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8442: algorithm to assign a block buffer to a block. That means that any
 8443: particular block can only be assigned to one specific block buffer,
 8444: called (for the particular operation) the @i{victim buffer}. If the
 8445: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8446: the new block immediately. If it is @i{assigned-dirty} its current
 8447: contents are written back to the blocks file on disk before it is
 8448: allocated to the new block.
 8449: 
 8450: Although no structure is imposed on the contents of a block, it is
 8451: traditional to display the contents as 16 lines each of 64 characters.  A
 8452: block provides a single, continuous stream of input (for example, it
 8453: acts as a single parse area) -- there are no end-of-line characters
 8454: within a block, and no end-of-file character at the end of a
 8455: block. There are two consequences of this:
 8456: 
 8457: @itemize @bullet
 8458: @item
 8459: The last character of one line wraps straight into the first character
 8460: of the following line
 8461: @item
 8462: The word @code{\} -- comment to end of line -- requires special
 8463: treatment; in the context of a block it causes all characters until the
 8464: end of the current 64-character ``line'' to be ignored.
 8465: @end itemize
 8466: 
 8467: In Gforth, when you use @code{block} with a non-existent block number,
 8468: the current blocks file will be extended to the appropriate size and the
 8469: block buffer will be initialised with spaces.
 8470: 
 8471: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8472: for details) but doesn't encourage the use of blocks; the mechanism is
 8473: only provided for backward compatibility -- ANS Forth requires blocks to
 8474: be available when files are.
 8475: 
 8476: Common techniques that are used when working with blocks include:
 8477: 
 8478: @itemize @bullet
 8479: @item
 8480: A screen editor that allows you to edit blocks without leaving the Forth
 8481: environment.
 8482: @item
 8483: Shadow screens; where every code block has an associated block
 8484: containing comments (for example: code in odd block numbers, comments in
 8485: even block numbers). Typically, the block editor provides a convenient
 8486: mechanism to toggle between code and comments.
 8487: @item
 8488: Load blocks; a single block (typically block 1) contains a number of
 8489: @code{thru} commands which @code{load} the whole of the application.
 8490: @end itemize
 8491: 
 8492: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8493: integrated into a Forth programming environment.
 8494: 
 8495: @comment TODO what about errors on open-blocks?
 8496: 
 8497: doc-open-blocks
 8498: doc-use
 8499: doc-block-offset
 8500: doc-get-block-fid
 8501: doc-block-position
 8502: 
 8503: doc-list
 8504: doc-scr
 8505: 
 8506: doc---gforthman-block
 8507: doc-buffer
 8508: 
 8509: doc-empty-buffers
 8510: doc-empty-buffer
 8511: doc-update
 8512: doc-updated?
 8513: doc-save-buffers
 8514: doc-save-buffer
 8515: doc-flush
 8516: 
 8517: doc-load
 8518: doc-thru
 8519: doc-+load
 8520: doc-+thru
 8521: doc---gforthman--->
 8522: doc-block-included
 8523: 
 8524: 
 8525: @c -------------------------------------------------------------
 8526: @node Other I/O, Locals, Blocks, Words
 8527: @section Other I/O
 8528: @cindex I/O - keyboard and display
 8529: 
 8530: @menu
 8531: * Simple numeric output::       Predefined formats
 8532: * Formatted numeric output::    Formatted (pictured) output
 8533: * String Formats::              How Forth stores strings in memory
 8534: * Displaying characters and strings::  Other stuff
 8535: * Input::                       Input
 8536: * Pipes::                       How to create your own pipes
 8537: @end menu
 8538: 
 8539: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8540: @subsection Simple numeric output
 8541: @cindex numeric output - simple/free-format
 8542: 
 8543: The simplest output functions are those that display numbers from the
 8544: data or floating-point stacks. Floating-point output is always displayed
 8545: using base 10. Numbers displayed from the data stack use the value stored
 8546: in @code{base}.
 8547: 
 8548: 
 8549: doc-.
 8550: doc-dec.
 8551: doc-hex.
 8552: doc-u.
 8553: doc-.r
 8554: doc-u.r
 8555: doc-d.
 8556: doc-ud.
 8557: doc-d.r
 8558: doc-ud.r
 8559: doc-f.
 8560: doc-fe.
 8561: doc-fs.
 8562: doc-f.rdp
 8563: 
 8564: Examples of printing the number 1234.5678E23 in the different floating-point output
 8565: formats are shown below:
 8566: 
 8567: @example
 8568: f. 123456779999999000000000000.
 8569: fe. 123.456779999999E24
 8570: fs. 1.23456779999999E26
 8571: @end example
 8572: 
 8573: 
 8574: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 8575: @subsection Formatted numeric output
 8576: @cindex formatted numeric output
 8577: @cindex pictured numeric output
 8578: @cindex numeric output - formatted
 8579: 
 8580: Forth traditionally uses a technique called @dfn{pictured numeric
 8581: output} for formatted printing of integers.  In this technique, digits
 8582: are extracted from the number (using the current output radix defined by
 8583: @code{base}), converted to ASCII codes and appended to a string that is
 8584: built in a scratch-pad area of memory (@pxref{core-idef,
 8585: Implementation-defined options, Implementation-defined
 8586: options}). Arbitrary characters can be appended to the string during the
 8587: extraction process. The completed string is specified by an address
 8588: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 8589: under program control.
 8590: 
 8591: All of the integer output words described in the previous section
 8592: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 8593: numeric output.
 8594: 
 8595: Three important things to remember about pictured numeric output:
 8596: 
 8597: @itemize @bullet
 8598: @item
 8599: It always operates on double-precision numbers; to display a
 8600: single-precision number, convert it first (for ways of doing this
 8601: @pxref{Double precision}).
 8602: @item
 8603: It always treats the double-precision number as though it were
 8604: unsigned. The examples below show ways of printing signed numbers.
 8605: @item
 8606: The string is built up from right to left; least significant digit first.
 8607: @end itemize
 8608: 
 8609: 
 8610: doc-<#
 8611: doc-<<#
 8612: doc-#
 8613: doc-#s
 8614: doc-hold
 8615: doc-sign
 8616: doc-#>
 8617: doc-#>>
 8618: 
 8619: doc-represent
 8620: doc-f>str-rdp
 8621: doc-f>buf-rdp
 8622: 
 8623: 
 8624: @noindent
 8625: Here are some examples of using pictured numeric output:
 8626: 
 8627: @example
 8628: : my-u. ( u -- )
 8629:   \ Simplest use of pns.. behaves like Standard u. 
 8630:   0              \ convert to unsigned double
 8631:   <<#            \ start conversion
 8632:   #s             \ convert all digits
 8633:   #>             \ complete conversion
 8634:   TYPE SPACE     \ display, with trailing space
 8635:   #>> ;          \ release hold area
 8636: 
 8637: : cents-only ( u -- )
 8638:   0              \ convert to unsigned double
 8639:   <<#            \ start conversion
 8640:   # #            \ convert two least-significant digits
 8641:   #>             \ complete conversion, discard other digits
 8642:   TYPE SPACE     \ display, with trailing space
 8643:   #>> ;          \ release hold area
 8644: 
 8645: : dollars-and-cents ( u -- )
 8646:   0              \ convert to unsigned double
 8647:   <<#            \ start conversion
 8648:   # #            \ convert two least-significant digits
 8649:   [char] . hold  \ insert decimal point
 8650:   #s             \ convert remaining digits
 8651:   [char] $ hold  \ append currency symbol
 8652:   #>             \ complete conversion
 8653:   TYPE SPACE     \ display, with trailing space
 8654:   #>> ;          \ release hold area
 8655: 
 8656: : my-. ( n -- )
 8657:   \ handling negatives.. behaves like Standard .
 8658:   s>d            \ convert to signed double
 8659:   swap over dabs \ leave sign byte followed by unsigned double
 8660:   <<#            \ start conversion
 8661:   #s             \ convert all digits
 8662:   rot sign       \ get at sign byte, append "-" if needed
 8663:   #>             \ complete conversion
 8664:   TYPE SPACE     \ display, with trailing space
 8665:   #>> ;          \ release hold area
 8666: 
 8667: : account. ( n -- )
 8668:   \ accountants don't like minus signs, they use parentheses
 8669:   \ for negative numbers
 8670:   s>d            \ convert to signed double
 8671:   swap over dabs \ leave sign byte followed by unsigned double
 8672:   <<#            \ start conversion
 8673:   2 pick         \ get copy of sign byte
 8674:   0< IF [char] ) hold THEN \ right-most character of output
 8675:   #s             \ convert all digits
 8676:   rot            \ get at sign byte
 8677:   0< IF [char] ( hold THEN
 8678:   #>             \ complete conversion
 8679:   TYPE SPACE     \ display, with trailing space
 8680:   #>> ;          \ release hold area
 8681: 
 8682: @end example
 8683: 
 8684: Here are some examples of using these words:
 8685: 
 8686: @example
 8687: 1 my-u. 1
 8688: hex -1 my-u. decimal FFFFFFFF
 8689: 1 cents-only 01
 8690: 1234 cents-only 34
 8691: 2 dollars-and-cents $0.02
 8692: 1234 dollars-and-cents $12.34
 8693: 123 my-. 123
 8694: -123 my. -123
 8695: 123 account. 123
 8696: -456 account. (456)
 8697: @end example
 8698: 
 8699: 
 8700: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 8701: @subsection String Formats
 8702: @cindex strings - see character strings
 8703: @cindex character strings - formats
 8704: @cindex I/O - see character strings
 8705: @cindex counted strings
 8706: 
 8707: @c anton: this does not really belong here; maybe the memory section,
 8708: @c  or the principles chapter
 8709: 
 8710: Forth commonly uses two different methods for representing character
 8711: strings:
 8712: 
 8713: @itemize @bullet
 8714: @item
 8715: @cindex address of counted string
 8716: @cindex counted string
 8717: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 8718: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 8719: string and the string occupies the subsequent @i{n} char addresses in
 8720: memory.
 8721: @item
 8722: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 8723: of the string in characters, and @i{c-addr} is the address of the
 8724: first byte of the string.
 8725: @end itemize
 8726: 
 8727: ANS Forth encourages the use of the second format when representing
 8728: strings.
 8729: 
 8730: 
 8731: doc-count
 8732: 
 8733: 
 8734: For words that move, copy and search for strings see @ref{Memory
 8735: Blocks}. For words that display characters and strings see
 8736: @ref{Displaying characters and strings}.
 8737: 
 8738: @node Displaying characters and strings, Input, String Formats, Other I/O
 8739: @subsection Displaying characters and strings
 8740: @cindex characters - compiling and displaying
 8741: @cindex character strings - compiling and displaying
 8742: 
 8743: This section starts with a glossary of Forth words and ends with a set
 8744: of examples.
 8745: 
 8746: 
 8747: doc-bl
 8748: doc-space
 8749: doc-spaces
 8750: doc-emit
 8751: doc-toupper
 8752: doc-."
 8753: doc-.(
 8754: doc-.\"
 8755: doc-type
 8756: doc-typewhite
 8757: doc-cr
 8758: @cindex cursor control
 8759: doc-at-xy
 8760: doc-page
 8761: doc-s"
 8762: doc-s\"
 8763: doc-c"
 8764: doc-char
 8765: doc-[char]
 8766: 
 8767: 
 8768: @noindent
 8769: As an example, consider the following text, stored in a file @file{test.fs}:
 8770: 
 8771: @example
 8772: .( text-1)
 8773: : my-word
 8774:   ." text-2" cr
 8775:   .( text-3)
 8776: ;
 8777: 
 8778: ." text-4"
 8779: 
 8780: : my-char
 8781:   [char] ALPHABET emit
 8782:   char emit
 8783: ;
 8784: @end example
 8785: 
 8786: When you load this code into Gforth, the following output is generated:
 8787: 
 8788: @example
 8789: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 8790: @end example
 8791: 
 8792: @itemize @bullet
 8793: @item
 8794: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 8795: is an immediate word; it behaves in the same way whether it is used inside
 8796: or outside a colon definition.
 8797: @item
 8798: Message @code{text-4} is displayed because of Gforth's added interpretation
 8799: semantics for @code{."}.
 8800: @item
 8801: Message @code{text-2} is @i{not} displayed, because the text interpreter
 8802: performs the compilation semantics for @code{."} within the definition of
 8803: @code{my-word}.
 8804: @end itemize
 8805: 
 8806: Here are some examples of executing @code{my-word} and @code{my-char}:
 8807: 
 8808: @example
 8809: @kbd{my-word @key{RET}} text-2
 8810:  ok
 8811: @kbd{my-char fred @key{RET}} Af ok
 8812: @kbd{my-char jim @key{RET}} Aj ok
 8813: @end example
 8814: 
 8815: @itemize @bullet
 8816: @item
 8817: Message @code{text-2} is displayed because of the run-time behaviour of
 8818: @code{."}.
 8819: @item
 8820: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 8821: on the stack at run-time. @code{emit} always displays the character
 8822: when @code{my-char} is executed.
 8823: @item
 8824: @code{char} parses a string at run-time and the second @code{emit} displays
 8825: the first character of the string.
 8826: @item
 8827: If you type @code{see my-char} you can see that @code{[char]} discarded
 8828: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 8829: definition of @code{my-char}.
 8830: @end itemize
 8831: 
 8832: 
 8833: 
 8834: @node Input, Pipes, Displaying characters and strings, Other I/O
 8835: @subsection Input
 8836: @cindex input
 8837: @cindex I/O - see input
 8838: @cindex parsing a string
 8839: 
 8840: For ways of storing character strings in memory see @ref{String Formats}.
 8841: 
 8842: @comment TODO examples for >number >float accept key key? pad parse word refill
 8843: @comment then index them
 8844: 
 8845: 
 8846: doc-key
 8847: doc-key?
 8848: doc-ekey
 8849: doc-ekey?
 8850: doc-ekey>char
 8851: doc->number
 8852: doc->float
 8853: doc-accept
 8854: doc-edit-line
 8855: doc-pad
 8856: @comment obsolescent words..
 8857: doc-convert
 8858: doc-expect
 8859: doc-span
 8860: 
 8861: 
 8862: @node Pipes,  , Input, Other I/O
 8863: @subsection Pipes
 8864: @cindex pipes, creating your own
 8865: 
 8866: In addition to using Gforth in pipes created by other processes
 8867: (@pxref{Gforth in pipes}), you can create your own pipe with
 8868: @code{open-pipe}, and read from or write to it.
 8869: 
 8870: doc-open-pipe
 8871: doc-close-pipe
 8872: 
 8873: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 8874: you don't catch this exception, Gforth will catch it and exit, usually
 8875: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 8876: this, you should wrap a @code{catch} or @code{try} block around the code
 8877: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 8878: problem yourself, and then return to regular processing.
 8879: 
 8880: doc-broken-pipe-error
 8881: 
 8882: 
 8883: @c -------------------------------------------------------------
 8884: @node Locals, Structures, Other I/O, Words
 8885: @section Locals
 8886: @cindex locals
 8887: 
 8888: Local variables can make Forth programming more enjoyable and Forth
 8889: programs easier to read. Unfortunately, the locals of ANS Forth are
 8890: laden with restrictions. Therefore, we provide not only the ANS Forth
 8891: locals wordset, but also our own, more powerful locals wordset (we
 8892: implemented the ANS Forth locals wordset through our locals wordset).
 8893: 
 8894: The ideas in this section have also been published in M. Anton Ertl,
 8895: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 8896: Automatic Scoping of Local Variables}}, EuroForth '94.
 8897: 
 8898: @menu
 8899: * Gforth locals::               
 8900: * ANS Forth locals::            
 8901: @end menu
 8902: 
 8903: @node Gforth locals, ANS Forth locals, Locals, Locals
 8904: @subsection Gforth locals
 8905: @cindex Gforth locals
 8906: @cindex locals, Gforth style
 8907: 
 8908: Locals can be defined with
 8909: 
 8910: @example
 8911: @{ local1 local2 ... -- comment @}
 8912: @end example
 8913: or
 8914: @example
 8915: @{ local1 local2 ... @}
 8916: @end example
 8917: 
 8918: E.g.,
 8919: @example
 8920: : max @{ n1 n2 -- n3 @}
 8921:  n1 n2 > if
 8922:    n1
 8923:  else
 8924:    n2
 8925:  endif ;
 8926: @end example
 8927: 
 8928: The similarity of locals definitions with stack comments is intended. A
 8929: locals definition often replaces the stack comment of a word. The order
 8930: of the locals corresponds to the order in a stack comment and everything
 8931: after the @code{--} is really a comment.
 8932: 
 8933: This similarity has one disadvantage: It is too easy to confuse locals
 8934: declarations with stack comments, causing bugs and making them hard to
 8935: find. However, this problem can be avoided by appropriate coding
 8936: conventions: Do not use both notations in the same program. If you do,
 8937: they should be distinguished using additional means, e.g. by position.
 8938: 
 8939: @cindex types of locals
 8940: @cindex locals types
 8941: The name of the local may be preceded by a type specifier, e.g.,
 8942: @code{F:} for a floating point value:
 8943: 
 8944: @example
 8945: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 8946: \ complex multiplication
 8947:  Ar Br f* Ai Bi f* f-
 8948:  Ar Bi f* Ai Br f* f+ ;
 8949: @end example
 8950: 
 8951: @cindex flavours of locals
 8952: @cindex locals flavours
 8953: @cindex value-flavoured locals
 8954: @cindex variable-flavoured locals
 8955: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 8956: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 8957: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 8958: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 8959: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 8960: produces its address (which becomes invalid when the variable's scope is
 8961: left). E.g., the standard word @code{emit} can be defined in terms of
 8962: @code{type} like this:
 8963: 
 8964: @example
 8965: : emit @{ C^ char* -- @}
 8966:     char* 1 type ;
 8967: @end example
 8968: 
 8969: @cindex default type of locals
 8970: @cindex locals, default type
 8971: A local without type specifier is a @code{W:} local. Both flavours of
 8972: locals are initialized with values from the data or FP stack.
 8973: 
 8974: Currently there is no way to define locals with user-defined data
 8975: structures, but we are working on it.
 8976: 
 8977: Gforth allows defining locals everywhere in a colon definition. This
 8978: poses the following questions:
 8979: 
 8980: @menu
 8981: * Where are locals visible by name?::  
 8982: * How long do locals live?::    
 8983: * Locals programming style::    
 8984: * Locals implementation::       
 8985: @end menu
 8986: 
 8987: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 8988: @subsubsection Where are locals visible by name?
 8989: @cindex locals visibility
 8990: @cindex visibility of locals
 8991: @cindex scope of locals
 8992: 
 8993: Basically, the answer is that locals are visible where you would expect
 8994: it in block-structured languages, and sometimes a little longer. If you
 8995: want to restrict the scope of a local, enclose its definition in
 8996: @code{SCOPE}...@code{ENDSCOPE}.
 8997: 
 8998: 
 8999: doc-scope
 9000: doc-endscope
 9001: 
 9002: 
 9003: These words behave like control structure words, so you can use them
 9004: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9005: arbitrary ways.
 9006: 
 9007: If you want a more exact answer to the visibility question, here's the
 9008: basic principle: A local is visible in all places that can only be
 9009: reached through the definition of the local@footnote{In compiler
 9010: construction terminology, all places dominated by the definition of the
 9011: local.}. In other words, it is not visible in places that can be reached
 9012: without going through the definition of the local. E.g., locals defined
 9013: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9014: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9015: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9016: 
 9017: The reasoning behind this solution is: We want to have the locals
 9018: visible as long as it is meaningful. The user can always make the
 9019: visibility shorter by using explicit scoping. In a place that can
 9020: only be reached through the definition of a local, the meaning of a
 9021: local name is clear. In other places it is not: How is the local
 9022: initialized at the control flow path that does not contain the
 9023: definition? Which local is meant, if the same name is defined twice in
 9024: two independent control flow paths?
 9025: 
 9026: This should be enough detail for nearly all users, so you can skip the
 9027: rest of this section. If you really must know all the gory details and
 9028: options, read on.
 9029: 
 9030: In order to implement this rule, the compiler has to know which places
 9031: are unreachable. It knows this automatically after @code{AHEAD},
 9032: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9033: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9034: compiler that the control flow never reaches that place. If
 9035: @code{UNREACHABLE} is not used where it could, the only consequence is
 9036: that the visibility of some locals is more limited than the rule above
 9037: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9038: lie to the compiler), buggy code will be produced.
 9039: 
 9040: 
 9041: doc-unreachable
 9042: 
 9043: 
 9044: Another problem with this rule is that at @code{BEGIN}, the compiler
 9045: does not know which locals will be visible on the incoming
 9046: back-edge. All problems discussed in the following are due to this
 9047: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9048: loops as examples; the discussion also applies to @code{?DO} and other
 9049: loops). Perhaps the most insidious example is:
 9050: @example
 9051: AHEAD
 9052: BEGIN
 9053:   x
 9054: [ 1 CS-ROLL ] THEN
 9055:   @{ x @}
 9056:   ...
 9057: UNTIL
 9058: @end example
 9059: 
 9060: This should be legal according to the visibility rule. The use of
 9061: @code{x} can only be reached through the definition; but that appears
 9062: textually below the use.
 9063: 
 9064: From this example it is clear that the visibility rules cannot be fully
 9065: implemented without major headaches. Our implementation treats common
 9066: cases as advertised and the exceptions are treated in a safe way: The
 9067: compiler makes a reasonable guess about the locals visible after a
 9068: @code{BEGIN}; if it is too pessimistic, the
 9069: user will get a spurious error about the local not being defined; if the
 9070: compiler is too optimistic, it will notice this later and issue a
 9071: warning. In the case above the compiler would complain about @code{x}
 9072: being undefined at its use. You can see from the obscure examples in
 9073: this section that it takes quite unusual control structures to get the
 9074: compiler into trouble, and even then it will often do fine.
 9075: 
 9076: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9077: is that all locals visible before the @code{BEGIN} will also be
 9078: visible after the @code{BEGIN}. This guess is valid for all loops that
 9079: are entered only through the @code{BEGIN}, in particular, for normal
 9080: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9081: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9082: compiler. When the branch to the @code{BEGIN} is finally generated by
 9083: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9084: warns the user if it was too optimistic:
 9085: @example
 9086: IF
 9087:   @{ x @}
 9088: BEGIN
 9089:   \ x ? 
 9090: [ 1 cs-roll ] THEN
 9091:   ...
 9092: UNTIL
 9093: @end example
 9094: 
 9095: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9096: optimistically assumes that it lives until the @code{THEN}. It notices
 9097: this difference when it compiles the @code{UNTIL} and issues a
 9098: warning. The user can avoid the warning, and make sure that @code{x}
 9099: is not used in the wrong area by using explicit scoping:
 9100: @example
 9101: IF
 9102:   SCOPE
 9103:   @{ x @}
 9104:   ENDSCOPE
 9105: BEGIN
 9106: [ 1 cs-roll ] THEN
 9107:   ...
 9108: UNTIL
 9109: @end example
 9110: 
 9111: Since the guess is optimistic, there will be no spurious error messages
 9112: about undefined locals.
 9113: 
 9114: If the @code{BEGIN} is not reachable from above (e.g., after
 9115: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9116: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9117: defined later. Therefore, the compiler assumes that no locals are
 9118: visible after the @code{BEGIN}. However, the user can use
 9119: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9120: visible at the BEGIN as at the point where the top control-flow stack
 9121: item was created.
 9122: 
 9123: 
 9124: doc-assume-live
 9125: 
 9126: 
 9127: @noindent
 9128: E.g.,
 9129: @example
 9130: @{ x @}
 9131: AHEAD
 9132: ASSUME-LIVE
 9133: BEGIN
 9134:   x
 9135: [ 1 CS-ROLL ] THEN
 9136:   ...
 9137: UNTIL
 9138: @end example
 9139: 
 9140: Other cases where the locals are defined before the @code{BEGIN} can be
 9141: handled by inserting an appropriate @code{CS-ROLL} before the
 9142: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9143: behind the @code{ASSUME-LIVE}).
 9144: 
 9145: Cases where locals are defined after the @code{BEGIN} (but should be
 9146: visible immediately after the @code{BEGIN}) can only be handled by
 9147: rearranging the loop. E.g., the ``most insidious'' example above can be
 9148: arranged into:
 9149: @example
 9150: BEGIN
 9151:   @{ x @}
 9152:   ... 0=
 9153: WHILE
 9154:   x
 9155: REPEAT
 9156: @end example
 9157: 
 9158: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9159: @subsubsection How long do locals live?
 9160: @cindex locals lifetime
 9161: @cindex lifetime of locals
 9162: 
 9163: The right answer for the lifetime question would be: A local lives at
 9164: least as long as it can be accessed. For a value-flavoured local this
 9165: means: until the end of its visibility. However, a variable-flavoured
 9166: local could be accessed through its address far beyond its visibility
 9167: scope. Ultimately, this would mean that such locals would have to be
 9168: garbage collected. Since this entails un-Forth-like implementation
 9169: complexities, I adopted the same cowardly solution as some other
 9170: languages (e.g., C): The local lives only as long as it is visible;
 9171: afterwards its address is invalid (and programs that access it
 9172: afterwards are erroneous).
 9173: 
 9174: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9175: @subsubsection Locals programming style
 9176: @cindex locals programming style
 9177: @cindex programming style, locals
 9178: 
 9179: The freedom to define locals anywhere has the potential to change
 9180: programming styles dramatically. In particular, the need to use the
 9181: return stack for intermediate storage vanishes. Moreover, all stack
 9182: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9183: determined arguments) can be eliminated: If the stack items are in the
 9184: wrong order, just write a locals definition for all of them; then
 9185: write the items in the order you want.
 9186: 
 9187: This seems a little far-fetched and eliminating stack manipulations is
 9188: unlikely to become a conscious programming objective. Still, the number
 9189: of stack manipulations will be reduced dramatically if local variables
 9190: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9191: a traditional implementation of @code{max}).
 9192: 
 9193: This shows one potential benefit of locals: making Forth programs more
 9194: readable. Of course, this benefit will only be realized if the
 9195: programmers continue to honour the principle of factoring instead of
 9196: using the added latitude to make the words longer.
 9197: 
 9198: @cindex single-assignment style for locals
 9199: Using @code{TO} can and should be avoided.  Without @code{TO},
 9200: every value-flavoured local has only a single assignment and many
 9201: advantages of functional languages apply to Forth. I.e., programs are
 9202: easier to analyse, to optimize and to read: It is clear from the
 9203: definition what the local stands for, it does not turn into something
 9204: different later.
 9205: 
 9206: E.g., a definition using @code{TO} might look like this:
 9207: @example
 9208: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9209:  u1 u2 min 0
 9210:  ?do
 9211:    addr1 c@@ addr2 c@@ -
 9212:    ?dup-if
 9213:      unloop exit
 9214:    then
 9215:    addr1 char+ TO addr1
 9216:    addr2 char+ TO addr2
 9217:  loop
 9218:  u1 u2 - ;
 9219: @end example
 9220: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9221: every loop iteration. @code{strcmp} is a typical example of the
 9222: readability problems of using @code{TO}. When you start reading
 9223: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9224: string. Only near the end of the loop you realize that it is something
 9225: else.
 9226: 
 9227: This can be avoided by defining two locals at the start of the loop that
 9228: are initialized with the right value for the current iteration.
 9229: @example
 9230: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9231:  addr1 addr2
 9232:  u1 u2 min 0 
 9233:  ?do @{ s1 s2 @}
 9234:    s1 c@@ s2 c@@ -
 9235:    ?dup-if
 9236:      unloop exit
 9237:    then
 9238:    s1 char+ s2 char+
 9239:  loop
 9240:  2drop
 9241:  u1 u2 - ;
 9242: @end example
 9243: Here it is clear from the start that @code{s1} has a different value
 9244: in every loop iteration.
 9245: 
 9246: @node Locals implementation,  , Locals programming style, Gforth locals
 9247: @subsubsection Locals implementation
 9248: @cindex locals implementation
 9249: @cindex implementation of locals
 9250: 
 9251: @cindex locals stack
 9252: Gforth uses an extra locals stack. The most compelling reason for
 9253: this is that the return stack is not float-aligned; using an extra stack
 9254: also eliminates the problems and restrictions of using the return stack
 9255: as locals stack. Like the other stacks, the locals stack grows toward
 9256: lower addresses. A few primitives allow an efficient implementation:
 9257: 
 9258: 
 9259: doc-@local#
 9260: doc-f@local#
 9261: doc-laddr#
 9262: doc-lp+!#
 9263: doc-lp!
 9264: doc->l
 9265: doc-f>l
 9266: 
 9267: 
 9268: In addition to these primitives, some specializations of these
 9269: primitives for commonly occurring inline arguments are provided for
 9270: efficiency reasons, e.g., @code{@@local0} as specialization of
 9271: @code{@@local#} for the inline argument 0. The following compiling words
 9272: compile the right specialized version, or the general version, as
 9273: appropriate:
 9274: 
 9275: 
 9276: @c doc-compile-@local
 9277: @c doc-compile-f@local
 9278: doc-compile-lp+!
 9279: 
 9280: 
 9281: Combinations of conditional branches and @code{lp+!#} like
 9282: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9283: is taken) are provided for efficiency and correctness in loops.
 9284: 
 9285: A special area in the dictionary space is reserved for keeping the
 9286: local variable names. @code{@{} switches the dictionary pointer to this
 9287: area and @code{@}} switches it back and generates the locals
 9288: initializing code. @code{W:} etc.@ are normal defining words. This
 9289: special area is cleared at the start of every colon definition.
 9290: 
 9291: @cindex word list for defining locals
 9292: A special feature of Gforth's dictionary is used to implement the
 9293: definition of locals without type specifiers: every word list (aka
 9294: vocabulary) has its own methods for searching
 9295: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
 9296: with a special search method: When it is searched for a word, it
 9297: actually creates that word using @code{W:}. @code{@{} changes the search
 9298: order to first search the word list containing @code{@}}, @code{W:} etc.,
 9299: and then the word list for defining locals without type specifiers.
 9300: 
 9301: The lifetime rules support a stack discipline within a colon
 9302: definition: The lifetime of a local is either nested with other locals
 9303: lifetimes or it does not overlap them.
 9304: 
 9305: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
 9306: pointer manipulation is generated. Between control structure words
 9307: locals definitions can push locals onto the locals stack. @code{AGAIN}
 9308: is the simplest of the other three control flow words. It has to
 9309: restore the locals stack depth of the corresponding @code{BEGIN}
 9310: before branching. The code looks like this:
 9311: @format
 9312: @code{lp+!#} current-locals-size @minus{} dest-locals-size
 9313: @code{branch} <begin>
 9314: @end format
 9315: 
 9316: @code{UNTIL} is a little more complicated: If it branches back, it
 9317: must adjust the stack just like @code{AGAIN}. But if it falls through,
 9318: the locals stack must not be changed. The compiler generates the
 9319: following code:
 9320: @format
 9321: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
 9322: @end format
 9323: The locals stack pointer is only adjusted if the branch is taken.
 9324: 
 9325: @code{THEN} can produce somewhat inefficient code:
 9326: @format
 9327: @code{lp+!#} current-locals-size @minus{} orig-locals-size
 9328: <orig target>:
 9329: @code{lp+!#} orig-locals-size @minus{} new-locals-size
 9330: @end format
 9331: The second @code{lp+!#} adjusts the locals stack pointer from the
 9332: level at the @i{orig} point to the level after the @code{THEN}. The
 9333: first @code{lp+!#} adjusts the locals stack pointer from the current
 9334: level to the level at the orig point, so the complete effect is an
 9335: adjustment from the current level to the right level after the
 9336: @code{THEN}.
 9337: 
 9338: @cindex locals information on the control-flow stack
 9339: @cindex control-flow stack items, locals information
 9340: In a conventional Forth implementation a dest control-flow stack entry
 9341: is just the target address and an orig entry is just the address to be
 9342: patched. Our locals implementation adds a word list to every orig or dest
 9343: item. It is the list of locals visible (or assumed visible) at the point
 9344: described by the entry. Our implementation also adds a tag to identify
 9345: the kind of entry, in particular to differentiate between live and dead
 9346: (reachable and unreachable) orig entries.
 9347: 
 9348: A few unusual operations have to be performed on locals word lists:
 9349: 
 9350: 
 9351: doc-common-list
 9352: doc-sub-list?
 9353: doc-list-size
 9354: 
 9355: 
 9356: Several features of our locals word list implementation make these
 9357: operations easy to implement: The locals word lists are organised as
 9358: linked lists; the tails of these lists are shared, if the lists
 9359: contain some of the same locals; and the address of a name is greater
 9360: than the address of the names behind it in the list.
 9361: 
 9362: Another important implementation detail is the variable
 9363: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
 9364: determine if they can be reached directly or only through the branch
 9365: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
 9366: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
 9367: definition, by @code{BEGIN} and usually by @code{THEN}.
 9368: 
 9369: Counted loops are similar to other loops in most respects, but
 9370: @code{LEAVE} requires special attention: It performs basically the same
 9371: service as @code{AHEAD}, but it does not create a control-flow stack
 9372: entry. Therefore the information has to be stored elsewhere;
 9373: traditionally, the information was stored in the target fields of the
 9374: branches created by the @code{LEAVE}s, by organizing these fields into a
 9375: linked list. Unfortunately, this clever trick does not provide enough
 9376: space for storing our extended control flow information. Therefore, we
 9377: introduce another stack, the leave stack. It contains the control-flow
 9378: stack entries for all unresolved @code{LEAVE}s.
 9379: 
 9380: Local names are kept until the end of the colon definition, even if
 9381: they are no longer visible in any control-flow path. In a few cases
 9382: this may lead to increased space needs for the locals name area, but
 9383: usually less than reclaiming this space would cost in code size.
 9384: 
 9385: 
 9386: @node ANS Forth locals,  , Gforth locals, Locals
 9387: @subsection ANS Forth locals
 9388: @cindex locals, ANS Forth style
 9389: 
 9390: The ANS Forth locals wordset does not define a syntax for locals, but
 9391: words that make it possible to define various syntaxes. One of the
 9392: possible syntaxes is a subset of the syntax we used in the Gforth locals
 9393: wordset, i.e.:
 9394: 
 9395: @example
 9396: @{ local1 local2 ... -- comment @}
 9397: @end example
 9398: @noindent
 9399: or
 9400: @example
 9401: @{ local1 local2 ... @}
 9402: @end example
 9403: 
 9404: The order of the locals corresponds to the order in a stack comment. The
 9405: restrictions are:
 9406: 
 9407: @itemize @bullet
 9408: @item
 9409: Locals can only be cell-sized values (no type specifiers are allowed).
 9410: @item
 9411: Locals can be defined only outside control structures.
 9412: @item
 9413: Locals can interfere with explicit usage of the return stack. For the
 9414: exact (and long) rules, see the standard. If you don't use return stack
 9415: accessing words in a definition using locals, you will be all right. The
 9416: purpose of this rule is to make locals implementation on the return
 9417: stack easier.
 9418: @item
 9419: The whole definition must be in one line.
 9420: @end itemize
 9421: 
 9422: Locals defined in ANS Forth behave like @code{VALUE}s
 9423: (@pxref{Values}). I.e., they are initialized from the stack. Using their
 9424: name produces their value. Their value can be changed using @code{TO}.
 9425: 
 9426: Since the syntax above is supported by Gforth directly, you need not do
 9427: anything to use it. If you want to port a program using this syntax to
 9428: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
 9429: syntax on the other system.
 9430: 
 9431: Note that a syntax shown in the standard, section A.13 looks
 9432: similar, but is quite different in having the order of locals
 9433: reversed. Beware!
 9434: 
 9435: The ANS Forth locals wordset itself consists of one word:
 9436: 
 9437: doc-(local)
 9438: 
 9439: The ANS Forth locals extension wordset defines a syntax using
 9440: @code{locals|}, but it is so awful that we strongly recommend not to use
 9441: it. We have implemented this syntax to make porting to Gforth easy, but
 9442: do not document it here. The problem with this syntax is that the locals
 9443: are defined in an order reversed with respect to the standard stack
 9444: comment notation, making programs harder to read, and easier to misread
 9445: and miswrite. The only merit of this syntax is that it is easy to
 9446: implement using the ANS Forth locals wordset.
 9447: 
 9448: 
 9449: @c ----------------------------------------------------------
 9450: @node Structures, Object-oriented Forth, Locals, Words
 9451: @section  Structures
 9452: @cindex structures
 9453: @cindex records
 9454: 
 9455: This section presents the structure package that comes with Gforth. A
 9456: version of the package implemented in ANS Forth is available in
 9457: @file{compat/struct.fs}. This package was inspired by a posting on
 9458: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
 9459: possibly John Hayes). A version of this section has been published in
 9460: M. Anton Ertl,
 9461: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
 9462: Another Forth Structures Package}, Forth Dimensions 19(3), pages
 9463: 13--16. Marcel Hendrix provided helpful comments.
 9464: 
 9465: @menu
 9466: * Why explicit structure support?::  
 9467: * Structure Usage::             
 9468: * Structure Naming Convention::  
 9469: * Structure Implementation::    
 9470: * Structure Glossary::          
 9471: @end menu
 9472: 
 9473: @node Why explicit structure support?, Structure Usage, Structures, Structures
 9474: @subsection Why explicit structure support?
 9475: 
 9476: @cindex address arithmetic for structures
 9477: @cindex structures using address arithmetic
 9478: If we want to use a structure containing several fields, we could simply
 9479: reserve memory for it, and access the fields using address arithmetic
 9480: (@pxref{Address arithmetic}). As an example, consider a structure with
 9481: the following fields
 9482: 
 9483: @table @code
 9484: @item a
 9485: is a float
 9486: @item b
 9487: is a cell
 9488: @item c
 9489: is a float
 9490: @end table
 9491: 
 9492: Given the (float-aligned) base address of the structure we get the
 9493: address of the field
 9494: 
 9495: @table @code
 9496: @item a
 9497: without doing anything further.
 9498: @item b
 9499: with @code{float+}
 9500: @item c
 9501: with @code{float+ cell+ faligned}
 9502: @end table
 9503: 
 9504: It is easy to see that this can become quite tiring. 
 9505: 
 9506: Moreover, it is not very readable, because seeing a
 9507: @code{cell+} tells us neither which kind of structure is
 9508: accessed nor what field is accessed; we have to somehow infer the kind
 9509: of structure, and then look up in the documentation, which field of
 9510: that structure corresponds to that offset.
 9511: 
 9512: Finally, this kind of address arithmetic also causes maintenance
 9513: troubles: If you add or delete a field somewhere in the middle of the
 9514: structure, you have to find and change all computations for the fields
 9515: afterwards.
 9516: 
 9517: So, instead of using @code{cell+} and friends directly, how
 9518: about storing the offsets in constants:
 9519: 
 9520: @example
 9521: 0 constant a-offset
 9522: 0 float+ constant b-offset
 9523: 0 float+ cell+ faligned c-offset
 9524: @end example
 9525: 
 9526: Now we can get the address of field @code{x} with @code{x-offset
 9527: +}. This is much better in all respects. Of course, you still
 9528: have to change all later offset definitions if you add a field. You can
 9529: fix this by declaring the offsets in the following way:
 9530: 
 9531: @example
 9532: 0 constant a-offset
 9533: a-offset float+ constant b-offset
 9534: b-offset cell+ faligned constant c-offset
 9535: @end example
 9536: 
 9537: Since we always use the offsets with @code{+}, we could use a defining
 9538: word @code{cfield} that includes the @code{+} in the action of the
 9539: defined word:
 9540: 
 9541: @example
 9542: : cfield ( n "name" -- )
 9543:     create ,
 9544: does> ( name execution: addr1 -- addr2 )
 9545:     @@ + ;
 9546: 
 9547: 0 cfield a
 9548: 0 a float+ cfield b
 9549: 0 b cell+ faligned cfield c
 9550: @end example
 9551: 
 9552: Instead of @code{x-offset +}, we now simply write @code{x}.
 9553: 
 9554: The structure field words now can be used quite nicely. However,
 9555: their definition is still a bit cumbersome: We have to repeat the
 9556: name, the information about size and alignment is distributed before
 9557: and after the field definitions etc.  The structure package presented
 9558: here addresses these problems.
 9559: 
 9560: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
 9561: @subsection Structure Usage
 9562: @cindex structure usage
 9563: 
 9564: @cindex @code{field} usage
 9565: @cindex @code{struct} usage
 9566: @cindex @code{end-struct} usage
 9567: You can define a structure for a (data-less) linked list with:
 9568: @example
 9569: struct
 9570:     cell% field list-next
 9571: end-struct list%
 9572: @end example
 9573: 
 9574: With the address of the list node on the stack, you can compute the
 9575: address of the field that contains the address of the next node with
 9576: @code{list-next}. E.g., you can determine the length of a list
 9577: with:
 9578: 
 9579: @example
 9580: : list-length ( list -- n )
 9581: \ "list" is a pointer to the first element of a linked list
 9582: \ "n" is the length of the list
 9583:     0 BEGIN ( list1 n1 )
 9584:         over
 9585:     WHILE ( list1 n1 )
 9586:         1+ swap list-next @@ swap
 9587:     REPEAT
 9588:     nip ;
 9589: @end example
 9590: 
 9591: You can reserve memory for a list node in the dictionary with
 9592: @code{list% %allot}, which leaves the address of the list node on the
 9593: stack. For the equivalent allocation on the heap you can use @code{list%
 9594: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
 9595: use @code{list% %allocate}). You can get the the size of a list
 9596: node with @code{list% %size} and its alignment with @code{list%
 9597: %alignment}.
 9598: 
 9599: Note that in ANS Forth the body of a @code{create}d word is
 9600: @code{aligned} but not necessarily @code{faligned};
 9601: therefore, if you do a:
 9602: 
 9603: @example
 9604: create @emph{name} foo% %allot drop
 9605: @end example
 9606: 
 9607: @noindent
 9608: then the memory alloted for @code{foo%} is guaranteed to start at the
 9609: body of @code{@emph{name}} only if @code{foo%} contains only character,
 9610: cell and double fields.  Therefore, if your structure contains floats,
 9611: better use
 9612: 
 9613: @example
 9614: foo% %allot constant @emph{name}
 9615: @end example
 9616: 
 9617: @cindex structures containing structures
 9618: You can include a structure @code{foo%} as a field of
 9619: another structure, like this:
 9620: @example
 9621: struct
 9622: ...
 9623:     foo% field ...
 9624: ...
 9625: end-struct ...
 9626: @end example
 9627: 
 9628: @cindex structure extension
 9629: @cindex extended records
 9630: Instead of starting with an empty structure, you can extend an
 9631: existing structure. E.g., a plain linked list without data, as defined
 9632: above, is hardly useful; You can extend it to a linked list of integers,
 9633: like this:@footnote{This feature is also known as @emph{extended
 9634: records}. It is the main innovation in the Oberon language; in other
 9635: words, adding this feature to Modula-2 led Wirth to create a new
 9636: language, write a new compiler etc.  Adding this feature to Forth just
 9637: required a few lines of code.}
 9638: 
 9639: @example
 9640: list%
 9641:     cell% field intlist-int
 9642: end-struct intlist%
 9643: @end example
 9644: 
 9645: @code{intlist%} is a structure with two fields:
 9646: @code{list-next} and @code{intlist-int}.
 9647: 
 9648: @cindex structures containing arrays
 9649: You can specify an array type containing @emph{n} elements of
 9650: type @code{foo%} like this:
 9651: 
 9652: @example
 9653: foo% @emph{n} *
 9654: @end example
 9655: 
 9656: You can use this array type in any place where you can use a normal
 9657: type, e.g., when defining a @code{field}, or with
 9658: @code{%allot}.
 9659: 
 9660: @cindex first field optimization
 9661: The first field is at the base address of a structure and the word for
 9662: this field (e.g., @code{list-next}) actually does not change the address
 9663: on the stack. You may be tempted to leave it away in the interest of
 9664: run-time and space efficiency. This is not necessary, because the
 9665: structure package optimizes this case: If you compile a first-field
 9666: words, no code is generated. So, in the interest of readability and
 9667: maintainability you should include the word for the field when accessing
 9668: the field.
 9669: 
 9670: 
 9671: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
 9672: @subsection Structure Naming Convention
 9673: @cindex structure naming convention
 9674: 
 9675: The field names that come to (my) mind are often quite generic, and,
 9676: if used, would cause frequent name clashes. E.g., many structures
 9677: probably contain a @code{counter} field. The structure names
 9678: that come to (my) mind are often also the logical choice for the names
 9679: of words that create such a structure.
 9680: 
 9681: Therefore, I have adopted the following naming conventions: 
 9682: 
 9683: @itemize @bullet
 9684: @cindex field naming convention
 9685: @item
 9686: The names of fields are of the form
 9687: @code{@emph{struct}-@emph{field}}, where
 9688: @code{@emph{struct}} is the basic name of the structure, and
 9689: @code{@emph{field}} is the basic name of the field. You can
 9690: think of field words as converting the (address of the)
 9691: structure into the (address of the) field.
 9692: 
 9693: @cindex structure naming convention
 9694: @item
 9695: The names of structures are of the form
 9696: @code{@emph{struct}%}, where
 9697: @code{@emph{struct}} is the basic name of the structure.
 9698: @end itemize
 9699: 
 9700: This naming convention does not work that well for fields of extended
 9701: structures; e.g., the integer list structure has a field
 9702: @code{intlist-int}, but has @code{list-next}, not
 9703: @code{intlist-next}.
 9704: 
 9705: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
 9706: @subsection Structure Implementation
 9707: @cindex structure implementation
 9708: @cindex implementation of structures
 9709: 
 9710: The central idea in the implementation is to pass the data about the
 9711: structure being built on the stack, not in some global
 9712: variable. Everything else falls into place naturally once this design
 9713: decision is made.
 9714: 
 9715: The type description on the stack is of the form @emph{align
 9716: size}. Keeping the size on the top-of-stack makes dealing with arrays
 9717: very simple.
 9718: 
 9719: @code{field} is a defining word that uses @code{Create}
 9720: and @code{DOES>}. The body of the field contains the offset
 9721: of the field, and the normal @code{DOES>} action is simply:
 9722: 
 9723: @example
 9724: @@ +
 9725: @end example
 9726: 
 9727: @noindent
 9728: i.e., add the offset to the address, giving the stack effect
 9729: @i{addr1 -- addr2} for a field.
 9730: 
 9731: @cindex first field optimization, implementation
 9732: This simple structure is slightly complicated by the optimization
 9733: for fields with offset 0, which requires a different
 9734: @code{DOES>}-part (because we cannot rely on there being
 9735: something on the stack if such a field is invoked during
 9736: compilation). Therefore, we put the different @code{DOES>}-parts
 9737: in separate words, and decide which one to invoke based on the
 9738: offset. For a zero offset, the field is basically a noop; it is
 9739: immediate, and therefore no code is generated when it is compiled.
 9740: 
 9741: @node Structure Glossary,  , Structure Implementation, Structures
 9742: @subsection Structure Glossary
 9743: @cindex structure glossary
 9744: 
 9745: 
 9746: doc-%align
 9747: doc-%alignment
 9748: doc-%alloc
 9749: doc-%allocate
 9750: doc-%allot
 9751: doc-cell%
 9752: doc-char%
 9753: doc-dfloat%
 9754: doc-double%
 9755: doc-end-struct
 9756: doc-field
 9757: doc-float%
 9758: doc-naligned
 9759: doc-sfloat%
 9760: doc-%size
 9761: doc-struct
 9762: 
 9763: 
 9764: @c -------------------------------------------------------------
 9765: @node Object-oriented Forth, Programming Tools, Structures, Words
 9766: @section Object-oriented Forth
 9767: 
 9768: Gforth comes with three packages for object-oriented programming:
 9769: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
 9770: is preloaded, so you have to @code{include} them before use. The most
 9771: important differences between these packages (and others) are discussed
 9772: in @ref{Comparison with other object models}. All packages are written
 9773: in ANS Forth and can be used with any other ANS Forth.
 9774: 
 9775: @menu
 9776: * Why object-oriented programming?::  
 9777: * Object-Oriented Terminology::  
 9778: * Objects::                     
 9779: * OOF::                         
 9780: * Mini-OOF::                    
 9781: * Comparison with other object models::  
 9782: @end menu
 9783: 
 9784: @c ----------------------------------------------------------------
 9785: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
 9786: @subsection Why object-oriented programming?
 9787: @cindex object-oriented programming motivation
 9788: @cindex motivation for object-oriented programming
 9789: 
 9790: Often we have to deal with several data structures (@emph{objects}),
 9791: that have to be treated similarly in some respects, but differently in
 9792: others. Graphical objects are the textbook example: circles, triangles,
 9793: dinosaurs, icons, and others, and we may want to add more during program
 9794: development. We want to apply some operations to any graphical object,
 9795: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
 9796: has to do something different for every kind of object.
 9797: @comment TODO add some other operations eg perimeter, area
 9798: @comment and tie in to concrete examples later..
 9799: 
 9800: We could implement @code{draw} as a big @code{CASE}
 9801: control structure that executes the appropriate code depending on the
 9802: kind of object to be drawn. This would be not be very elegant, and,
 9803: moreover, we would have to change @code{draw} every time we add
 9804: a new kind of graphical object (say, a spaceship).
 9805: 
 9806: What we would rather do is: When defining spaceships, we would tell
 9807: the system: ``Here's how you @code{draw} a spaceship; you figure
 9808: out the rest''.
 9809: 
 9810: This is the problem that all systems solve that (rightfully) call
 9811: themselves object-oriented; the object-oriented packages presented here
 9812: solve this problem (and not much else).
 9813: @comment TODO ?list properties of oo systems.. oo vs o-based?
 9814: 
 9815: @c ------------------------------------------------------------------------
 9816: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
 9817: @subsection Object-Oriented Terminology
 9818: @cindex object-oriented terminology
 9819: @cindex terminology for object-oriented programming
 9820: 
 9821: This section is mainly for reference, so you don't have to understand
 9822: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
 9823: short:
 9824: 
 9825: @table @emph
 9826: @cindex class
 9827: @item class
 9828: a data structure definition with some extras.
 9829: 
 9830: @cindex object
 9831: @item object
 9832: an instance of the data structure described by the class definition.
 9833: 
 9834: @cindex instance variables
 9835: @item instance variables
 9836: fields of the data structure.
 9837: 
 9838: @cindex selector
 9839: @cindex method selector
 9840: @cindex virtual function
 9841: @item selector
 9842: (or @emph{method selector}) a word (e.g.,
 9843: @code{draw}) that performs an operation on a variety of data
 9844: structures (classes). A selector describes @emph{what} operation to
 9845: perform. In C++ terminology: a (pure) virtual function.
 9846: 
 9847: @cindex method
 9848: @item method
 9849: the concrete definition that performs the operation
 9850: described by the selector for a specific class. A method specifies
 9851: @emph{how} the operation is performed for a specific class.
 9852: 
 9853: @cindex selector invocation
 9854: @cindex message send
 9855: @cindex invoking a selector
 9856: @item selector invocation
 9857: a call of a selector. One argument of the call (the TOS (top-of-stack))
 9858: is used for determining which method is used. In Smalltalk terminology:
 9859: a message (consisting of the selector and the other arguments) is sent
 9860: to the object.
 9861: 
 9862: @cindex receiving object
 9863: @item receiving object
 9864: the object used for determining the method executed by a selector
 9865: invocation. In the @file{objects.fs} model, it is the object that is on
 9866: the TOS when the selector is invoked. (@emph{Receiving} comes from
 9867: the Smalltalk @emph{message} terminology.)
 9868: 
 9869: @cindex child class
 9870: @cindex parent class
 9871: @cindex inheritance
 9872: @item child class
 9873: a class that has (@emph{inherits}) all properties (instance variables,
 9874: selectors, methods) from a @emph{parent class}. In Smalltalk
 9875: terminology: The subclass inherits from the superclass. In C++
 9876: terminology: The derived class inherits from the base class.
 9877: 
 9878: @end table
 9879: 
 9880: @c If you wonder about the message sending terminology, it comes from
 9881: @c a time when each object had it's own task and objects communicated via
 9882: @c message passing; eventually the Smalltalk developers realized that
 9883: @c they can do most things through simple (indirect) calls. They kept the
 9884: @c terminology.
 9885: 
 9886: @c --------------------------------------------------------------
 9887: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
 9888: @subsection The @file{objects.fs} model
 9889: @cindex objects
 9890: @cindex object-oriented programming
 9891: 
 9892: @cindex @file{objects.fs}
 9893: @cindex @file{oof.fs}
 9894: 
 9895: This section describes the @file{objects.fs} package. This material also
 9896: has been published in M. Anton Ertl,
 9897: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
 9898: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
 9899: 37--43.
 9900: @c McKewan's and Zsoter's packages
 9901: 
 9902: This section assumes that you have read @ref{Structures}.
 9903: 
 9904: The techniques on which this model is based have been used to implement
 9905: the parser generator, Gray, and have also been used in Gforth for
 9906: implementing the various flavours of word lists (hashed or not,
 9907: case-sensitive or not, special-purpose word lists for locals etc.).
 9908: 
 9909: 
 9910: @menu
 9911: * Properties of the Objects model::  
 9912: * Basic Objects Usage::         
 9913: * The Objects base class::      
 9914: * Creating objects::            
 9915: * Object-Oriented Programming Style::  
 9916: * Class Binding::               
 9917: * Method conveniences::         
 9918: * Classes and Scoping::         
 9919: * Dividing classes::            
 9920: * Object Interfaces::           
 9921: * Objects Implementation::      
 9922: * Objects Glossary::            
 9923: @end menu
 9924: 
 9925: Marcel Hendrix provided helpful comments on this section.
 9926: 
 9927: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
 9928: @subsubsection Properties of the @file{objects.fs} model
 9929: @cindex @file{objects.fs} properties
 9930: 
 9931: @itemize @bullet
 9932: @item
 9933: It is straightforward to pass objects on the stack. Passing
 9934: selectors on the stack is a little less convenient, but possible.
 9935: 
 9936: @item
 9937: Objects are just data structures in memory, and are referenced by their
 9938: address. You can create words for objects with normal defining words
 9939: like @code{constant}. Likewise, there is no difference between instance
 9940: variables that contain objects and those that contain other data.
 9941: 
 9942: @item
 9943: Late binding is efficient and easy to use.
 9944: 
 9945: @item
 9946: It avoids parsing, and thus avoids problems with state-smartness
 9947: and reduced extensibility; for convenience there are a few parsing
 9948: words, but they have non-parsing counterparts. There are also a few
 9949: defining words that parse. This is hard to avoid, because all standard
 9950: defining words parse (except @code{:noname}); however, such
 9951: words are not as bad as many other parsing words, because they are not
 9952: state-smart.
 9953: 
 9954: @item
 9955: It does not try to incorporate everything. It does a few things and does
 9956: them well (IMO). In particular, this model was not designed to support
 9957: information hiding (although it has features that may help); you can use
 9958: a separate package for achieving this.
 9959: 
 9960: @item
 9961: It is layered; you don't have to learn and use all features to use this
 9962: model. Only a few features are necessary (@pxref{Basic Objects Usage},
 9963: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
 9964: are optional and independent of each other.
 9965: 
 9966: @item
 9967: An implementation in ANS Forth is available.
 9968: 
 9969: @end itemize
 9970: 
 9971: 
 9972: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
 9973: @subsubsection Basic @file{objects.fs} Usage
 9974: @cindex basic objects usage
 9975: @cindex objects, basic usage
 9976: 
 9977: You can define a class for graphical objects like this:
 9978: 
 9979: @cindex @code{class} usage
 9980: @cindex @code{end-class} usage
 9981: @cindex @code{selector} usage
 9982: @example
 9983: object class \ "object" is the parent class
 9984:   selector draw ( x y graphical -- )
 9985: end-class graphical
 9986: @end example
 9987: 
 9988: This code defines a class @code{graphical} with an
 9989: operation @code{draw}.  We can perform the operation
 9990: @code{draw} on any @code{graphical} object, e.g.:
 9991: 
 9992: @example
 9993: 100 100 t-rex draw
 9994: @end example
 9995: 
 9996: @noindent
 9997: where @code{t-rex} is a word (say, a constant) that produces a
 9998: graphical object.
 9999: 
10000: @comment TODO add a 2nd operation eg perimeter.. and use for
10001: @comment a concrete example
10002: 
10003: @cindex abstract class
10004: How do we create a graphical object? With the present definitions,
10005: we cannot create a useful graphical object. The class
10006: @code{graphical} describes graphical objects in general, but not
10007: any concrete graphical object type (C++ users would call it an
10008: @emph{abstract class}); e.g., there is no method for the selector
10009: @code{draw} in the class @code{graphical}.
10010: 
10011: For concrete graphical objects, we define child classes of the
10012: class @code{graphical}, e.g.:
10013: 
10014: @cindex @code{overrides} usage
10015: @cindex @code{field} usage in class definition
10016: @example
10017: graphical class \ "graphical" is the parent class
10018:   cell% field circle-radius
10019: 
10020: :noname ( x y circle -- )
10021:   circle-radius @@ draw-circle ;
10022: overrides draw
10023: 
10024: :noname ( n-radius circle -- )
10025:   circle-radius ! ;
10026: overrides construct
10027: 
10028: end-class circle
10029: @end example
10030: 
10031: Here we define a class @code{circle} as a child of @code{graphical},
10032: with field @code{circle-radius} (which behaves just like a field
10033: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10034: for the selectors @code{draw} and @code{construct} (@code{construct} is
10035: defined in @code{object}, the parent class of @code{graphical}).
10036: 
10037: Now we can create a circle on the heap (i.e.,
10038: @code{allocate}d memory) with:
10039: 
10040: @cindex @code{heap-new} usage
10041: @example
10042: 50 circle heap-new constant my-circle
10043: @end example
10044: 
10045: @noindent
10046: @code{heap-new} invokes @code{construct}, thus
10047: initializing the field @code{circle-radius} with 50. We can draw
10048: this new circle at (100,100) with:
10049: 
10050: @example
10051: 100 100 my-circle draw
10052: @end example
10053: 
10054: @cindex selector invocation, restrictions
10055: @cindex class definition, restrictions
10056: Note: You can only invoke a selector if the object on the TOS
10057: (the receiving object) belongs to the class where the selector was
10058: defined or one of its descendents; e.g., you can invoke
10059: @code{draw} only for objects belonging to @code{graphical}
10060: or its descendents (e.g., @code{circle}).  Immediately before
10061: @code{end-class}, the search order has to be the same as
10062: immediately after @code{class}.
10063: 
10064: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10065: @subsubsection The @file{object.fs} base class
10066: @cindex @code{object} class
10067: 
10068: When you define a class, you have to specify a parent class.  So how do
10069: you start defining classes? There is one class available from the start:
10070: @code{object}. It is ancestor for all classes and so is the
10071: only class that has no parent. It has two selectors: @code{construct}
10072: and @code{print}.
10073: 
10074: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10075: @subsubsection Creating objects
10076: @cindex creating objects
10077: @cindex object creation
10078: @cindex object allocation options
10079: 
10080: @cindex @code{heap-new} discussion
10081: @cindex @code{dict-new} discussion
10082: @cindex @code{construct} discussion
10083: You can create and initialize an object of a class on the heap with
10084: @code{heap-new} ( ... class -- object ) and in the dictionary
10085: (allocation with @code{allot}) with @code{dict-new} (
10086: ... class -- object ). Both words invoke @code{construct}, which
10087: consumes the stack items indicated by "..." above.
10088: 
10089: @cindex @code{init-object} discussion
10090: @cindex @code{class-inst-size} discussion
10091: If you want to allocate memory for an object yourself, you can get its
10092: alignment and size with @code{class-inst-size 2@@} ( class --
10093: align size ). Once you have memory for an object, you can initialize
10094: it with @code{init-object} ( ... class object -- );
10095: @code{construct} does only a part of the necessary work.
10096: 
10097: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10098: @subsubsection Object-Oriented Programming Style
10099: @cindex object-oriented programming style
10100: @cindex programming style, object-oriented
10101: 
10102: This section is not exhaustive.
10103: 
10104: @cindex stack effects of selectors
10105: @cindex selectors and stack effects
10106: In general, it is a good idea to ensure that all methods for the
10107: same selector have the same stack effect: when you invoke a selector,
10108: you often have no idea which method will be invoked, so, unless all
10109: methods have the same stack effect, you will not know the stack effect
10110: of the selector invocation.
10111: 
10112: One exception to this rule is methods for the selector
10113: @code{construct}. We know which method is invoked, because we
10114: specify the class to be constructed at the same place. Actually, I
10115: defined @code{construct} as a selector only to give the users a
10116: convenient way to specify initialization. The way it is used, a
10117: mechanism different from selector invocation would be more natural
10118: (but probably would take more code and more space to explain).
10119: 
10120: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10121: @subsubsection Class Binding
10122: @cindex class binding
10123: @cindex early binding
10124: 
10125: @cindex late binding
10126: Normal selector invocations determine the method at run-time depending
10127: on the class of the receiving object. This run-time selection is called
10128: @i{late binding}.
10129: 
10130: Sometimes it's preferable to invoke a different method. For example,
10131: you might want to use the simple method for @code{print}ing
10132: @code{object}s instead of the possibly long-winded @code{print} method
10133: of the receiver class. You can achieve this by replacing the invocation
10134: of @code{print} with:
10135: 
10136: @cindex @code{[bind]} usage
10137: @example
10138: [bind] object print
10139: @end example
10140: 
10141: @noindent
10142: in compiled code or:
10143: 
10144: @cindex @code{bind} usage
10145: @example
10146: bind object print
10147: @end example
10148: 
10149: @cindex class binding, alternative to
10150: @noindent
10151: in interpreted code. Alternatively, you can define the method with a
10152: name (e.g., @code{print-object}), and then invoke it through the
10153: name. Class binding is just a (often more convenient) way to achieve
10154: the same effect; it avoids name clutter and allows you to invoke
10155: methods directly without naming them first.
10156: 
10157: @cindex superclass binding
10158: @cindex parent class binding
10159: A frequent use of class binding is this: When we define a method
10160: for a selector, we often want the method to do what the selector does
10161: in the parent class, and a little more. There is a special word for
10162: this purpose: @code{[parent]}; @code{[parent]
10163: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10164: selector}}, where @code{@emph{parent}} is the parent
10165: class of the current class. E.g., a method definition might look like:
10166: 
10167: @cindex @code{[parent]} usage
10168: @example
10169: :noname
10170:   dup [parent] foo \ do parent's foo on the receiving object
10171:   ... \ do some more
10172: ; overrides foo
10173: @end example
10174: 
10175: @cindex class binding as optimization
10176: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10177: March 1997), Andrew McKewan presents class binding as an optimization
10178: technique. I recommend not using it for this purpose unless you are in
10179: an emergency. Late binding is pretty fast with this model anyway, so the
10180: benefit of using class binding is small; the cost of using class binding
10181: where it is not appropriate is reduced maintainability.
10182: 
10183: While we are at programming style questions: You should bind
10184: selectors only to ancestor classes of the receiving object. E.g., say,
10185: you know that the receiving object is of class @code{foo} or its
10186: descendents; then you should bind only to @code{foo} and its
10187: ancestors.
10188: 
10189: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10190: @subsubsection Method conveniences
10191: @cindex method conveniences
10192: 
10193: In a method you usually access the receiving object pretty often.  If
10194: you define the method as a plain colon definition (e.g., with
10195: @code{:noname}), you may have to do a lot of stack
10196: gymnastics. To avoid this, you can define the method with @code{m:
10197: ... ;m}. E.g., you could define the method for
10198: @code{draw}ing a @code{circle} with
10199: 
10200: @cindex @code{this} usage
10201: @cindex @code{m:} usage
10202: @cindex @code{;m} usage
10203: @example
10204: m: ( x y circle -- )
10205:   ( x y ) this circle-radius @@ draw-circle ;m
10206: @end example
10207: 
10208: @cindex @code{exit} in @code{m: ... ;m}
10209: @cindex @code{exitm} discussion
10210: @cindex @code{catch} in @code{m: ... ;m}
10211: When this method is executed, the receiver object is removed from the
10212: stack; you can access it with @code{this} (admittedly, in this
10213: example the use of @code{m: ... ;m} offers no advantage). Note
10214: that I specify the stack effect for the whole method (i.e. including
10215: the receiver object), not just for the code between @code{m:}
10216: and @code{;m}. You cannot use @code{exit} in
10217: @code{m:...;m}; instead, use
10218: @code{exitm}.@footnote{Moreover, for any word that calls
10219: @code{catch} and was defined before loading
10220: @code{objects.fs}, you have to redefine it like I redefined
10221: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10222: 
10223: @cindex @code{inst-var} usage
10224: You will frequently use sequences of the form @code{this
10225: @emph{field}} (in the example above: @code{this
10226: circle-radius}). If you use the field only in this way, you can
10227: define it with @code{inst-var} and eliminate the
10228: @code{this} before the field name. E.g., the @code{circle}
10229: class above could also be defined with:
10230: 
10231: @example
10232: graphical class
10233:   cell% inst-var radius
10234: 
10235: m: ( x y circle -- )
10236:   radius @@ draw-circle ;m
10237: overrides draw
10238: 
10239: m: ( n-radius circle -- )
10240:   radius ! ;m
10241: overrides construct
10242: 
10243: end-class circle
10244: @end example
10245: 
10246: @code{radius} can only be used in @code{circle} and its
10247: descendent classes and inside @code{m:...;m}.
10248: 
10249: @cindex @code{inst-value} usage
10250: You can also define fields with @code{inst-value}, which is
10251: to @code{inst-var} what @code{value} is to
10252: @code{variable}.  You can change the value of such a field with
10253: @code{[to-inst]}.  E.g., we could also define the class
10254: @code{circle} like this:
10255: 
10256: @example
10257: graphical class
10258:   inst-value radius
10259: 
10260: m: ( x y circle -- )
10261:   radius draw-circle ;m
10262: overrides draw
10263: 
10264: m: ( n-radius circle -- )
10265:   [to-inst] radius ;m
10266: overrides construct
10267: 
10268: end-class circle
10269: @end example
10270: 
10271: @c !! :m is easy to confuse with m:.  Another name would be better.
10272: 
10273: @c Finally, you can define named methods with @code{:m}.  One use of this
10274: @c feature is the definition of words that occur only in one class and are
10275: @c not intended to be overridden, but which still need method context
10276: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
10277: @c would be bound frequently, if defined anonymously.
10278: 
10279: 
10280: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10281: @subsubsection Classes and Scoping
10282: @cindex classes and scoping
10283: @cindex scoping and classes
10284: 
10285: Inheritance is frequent, unlike structure extension. This exacerbates
10286: the problem with the field name convention (@pxref{Structure Naming
10287: Convention}): One always has to remember in which class the field was
10288: originally defined; changing a part of the class structure would require
10289: changes for renaming in otherwise unaffected code.
10290: 
10291: @cindex @code{inst-var} visibility
10292: @cindex @code{inst-value} visibility
10293: To solve this problem, I added a scoping mechanism (which was not in my
10294: original charter): A field defined with @code{inst-var} (or
10295: @code{inst-value}) is visible only in the class where it is defined and in
10296: the descendent classes of this class.  Using such fields only makes
10297: sense in @code{m:}-defined methods in these classes anyway.
10298: 
10299: This scoping mechanism allows us to use the unadorned field name,
10300: because name clashes with unrelated words become much less likely.
10301: 
10302: @cindex @code{protected} discussion
10303: @cindex @code{private} discussion
10304: Once we have this mechanism, we can also use it for controlling the
10305: visibility of other words: All words defined after
10306: @code{protected} are visible only in the current class and its
10307: descendents. @code{public} restores the compilation
10308: (i.e. @code{current}) word list that was in effect before. If you
10309: have several @code{protected}s without an intervening
10310: @code{public} or @code{set-current}, @code{public}
10311: will restore the compilation word list in effect before the first of
10312: these @code{protected}s.
10313: 
10314: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10315: @subsubsection Dividing classes
10316: @cindex Dividing classes
10317: @cindex @code{methods}...@code{end-methods}
10318: 
10319: You may want to do the definition of methods separate from the
10320: definition of the class, its selectors, fields, and instance variables,
10321: i.e., separate the implementation from the definition.  You can do this
10322: in the following way:
10323: 
10324: @example
10325: graphical class
10326:   inst-value radius
10327: end-class circle
10328: 
10329: ... \ do some other stuff
10330: 
10331: circle methods \ now we are ready
10332: 
10333: m: ( x y circle -- )
10334:   radius draw-circle ;m
10335: overrides draw
10336: 
10337: m: ( n-radius circle -- )
10338:   [to-inst] radius ;m
10339: overrides construct
10340: 
10341: end-methods
10342: @end example
10343: 
10344: You can use several @code{methods}...@code{end-methods} sections.  The
10345: only things you can do to the class in these sections are: defining
10346: methods, and overriding the class's selectors.  You must not define new
10347: selectors or fields.
10348: 
10349: Note that you often have to override a selector before using it.  In
10350: particular, you usually have to override @code{construct} with a new
10351: method before you can invoke @code{heap-new} and friends.  E.g., you
10352: must not create a circle before the @code{overrides construct} sequence
10353: in the example above.
10354: 
10355: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10356: @subsubsection Object Interfaces
10357: @cindex object interfaces
10358: @cindex interfaces for objects
10359: 
10360: In this model you can only call selectors defined in the class of the
10361: receiving objects or in one of its ancestors. If you call a selector
10362: with a receiving object that is not in one of these classes, the
10363: result is undefined; if you are lucky, the program crashes
10364: immediately.
10365: 
10366: @cindex selectors common to hardly-related classes
10367: Now consider the case when you want to have a selector (or several)
10368: available in two classes: You would have to add the selector to a
10369: common ancestor class, in the worst case to @code{object}. You
10370: may not want to do this, e.g., because someone else is responsible for
10371: this ancestor class.
10372: 
10373: The solution for this problem is interfaces. An interface is a
10374: collection of selectors. If a class implements an interface, the
10375: selectors become available to the class and its descendents. A class
10376: can implement an unlimited number of interfaces. For the problem
10377: discussed above, we would define an interface for the selector(s), and
10378: both classes would implement the interface.
10379: 
10380: As an example, consider an interface @code{storage} for
10381: writing objects to disk and getting them back, and a class
10382: @code{foo} that implements it. The code would look like this:
10383: 
10384: @cindex @code{interface} usage
10385: @cindex @code{end-interface} usage
10386: @cindex @code{implementation} usage
10387: @example
10388: interface
10389:   selector write ( file object -- )
10390:   selector read1 ( file object -- )
10391: end-interface storage
10392: 
10393: bar class
10394:   storage implementation
10395: 
10396: ... overrides write
10397: ... overrides read1
10398: ...
10399: end-class foo
10400: @end example
10401: 
10402: @noindent
10403: (I would add a word @code{read} @i{( file -- object )} that uses
10404: @code{read1} internally, but that's beyond the point illustrated
10405: here.)
10406: 
10407: Note that you cannot use @code{protected} in an interface; and
10408: of course you cannot define fields.
10409: 
10410: In the Neon model, all selectors are available for all classes;
10411: therefore it does not need interfaces. The price you pay in this model
10412: is slower late binding, and therefore, added complexity to avoid late
10413: binding.
10414: 
10415: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10416: @subsubsection @file{objects.fs} Implementation
10417: @cindex @file{objects.fs} implementation
10418: 
10419: @cindex @code{object-map} discussion
10420: An object is a piece of memory, like one of the data structures
10421: described with @code{struct...end-struct}. It has a field
10422: @code{object-map} that points to the method map for the object's
10423: class.
10424: 
10425: @cindex method map
10426: @cindex virtual function table
10427: The @emph{method map}@footnote{This is Self terminology; in C++
10428: terminology: virtual function table.} is an array that contains the
10429: execution tokens (@i{xt}s) of the methods for the object's class. Each
10430: selector contains an offset into a method map.
10431: 
10432: @cindex @code{selector} implementation, class
10433: @code{selector} is a defining word that uses
10434: @code{CREATE} and @code{DOES>}. The body of the
10435: selector contains the offset; the @code{DOES>} action for a
10436: class selector is, basically:
10437: 
10438: @example
10439: ( object addr ) @@ over object-map @@ + @@ execute
10440: @end example
10441: 
10442: Since @code{object-map} is the first field of the object, it
10443: does not generate any code. As you can see, calling a selector has a
10444: small, constant cost.
10445: 
10446: @cindex @code{current-interface} discussion
10447: @cindex class implementation and representation
10448: A class is basically a @code{struct} combined with a method
10449: map. During the class definition the alignment and size of the class
10450: are passed on the stack, just as with @code{struct}s, so
10451: @code{field} can also be used for defining class
10452: fields. However, passing more items on the stack would be
10453: inconvenient, so @code{class} builds a data structure in memory,
10454: which is accessed through the variable
10455: @code{current-interface}. After its definition is complete, the
10456: class is represented on the stack by a pointer (e.g., as parameter for
10457: a child class definition).
10458: 
10459: A new class starts off with the alignment and size of its parent,
10460: and a copy of the parent's method map. Defining new fields extends the
10461: size and alignment; likewise, defining new selectors extends the
10462: method map. @code{overrides} just stores a new @i{xt} in the method
10463: map at the offset given by the selector.
10464: 
10465: @cindex class binding, implementation
10466: Class binding just gets the @i{xt} at the offset given by the selector
10467: from the class's method map and @code{compile,}s (in the case of
10468: @code{[bind]}) it.
10469: 
10470: @cindex @code{this} implementation
10471: @cindex @code{catch} and @code{this}
10472: @cindex @code{this} and @code{catch}
10473: I implemented @code{this} as a @code{value}. At the
10474: start of an @code{m:...;m} method the old @code{this} is
10475: stored to the return stack and restored at the end; and the object on
10476: the TOS is stored @code{TO this}. This technique has one
10477: disadvantage: If the user does not leave the method via
10478: @code{;m}, but via @code{throw} or @code{exit},
10479: @code{this} is not restored (and @code{exit} may
10480: crash). To deal with the @code{throw} problem, I have redefined
10481: @code{catch} to save and restore @code{this}; the same
10482: should be done with any word that can catch an exception. As for
10483: @code{exit}, I simply forbid it (as a replacement, there is
10484: @code{exitm}).
10485: 
10486: @cindex @code{inst-var} implementation
10487: @code{inst-var} is just the same as @code{field}, with
10488: a different @code{DOES>} action:
10489: @example
10490: @@ this +
10491: @end example
10492: Similar for @code{inst-value}.
10493: 
10494: @cindex class scoping implementation
10495: Each class also has a word list that contains the words defined with
10496: @code{inst-var} and @code{inst-value}, and its protected
10497: words. It also has a pointer to its parent. @code{class} pushes
10498: the word lists of the class and all its ancestors onto the search order stack,
10499: and @code{end-class} drops them.
10500: 
10501: @cindex interface implementation
10502: An interface is like a class without fields, parent and protected
10503: words; i.e., it just has a method map. If a class implements an
10504: interface, its method map contains a pointer to the method map of the
10505: interface. The positive offsets in the map are reserved for class
10506: methods, therefore interface map pointers have negative
10507: offsets. Interfaces have offsets that are unique throughout the
10508: system, unlike class selectors, whose offsets are only unique for the
10509: classes where the selector is available (invokable).
10510: 
10511: This structure means that interface selectors have to perform one
10512: indirection more than class selectors to find their method. Their body
10513: contains the interface map pointer offset in the class method map, and
10514: the method offset in the interface method map. The
10515: @code{does>} action for an interface selector is, basically:
10516: 
10517: @example
10518: ( object selector-body )
10519: 2dup selector-interface @@ ( object selector-body object interface-offset )
10520: swap object-map @@ + @@ ( object selector-body map )
10521: swap selector-offset @@ + @@ execute
10522: @end example
10523: 
10524: where @code{object-map} and @code{selector-offset} are
10525: first fields and generate no code.
10526: 
10527: As a concrete example, consider the following code:
10528: 
10529: @example
10530: interface
10531:   selector if1sel1
10532:   selector if1sel2
10533: end-interface if1
10534: 
10535: object class
10536:   if1 implementation
10537:   selector cl1sel1
10538:   cell% inst-var cl1iv1
10539: 
10540: ' m1 overrides construct
10541: ' m2 overrides if1sel1
10542: ' m3 overrides if1sel2
10543: ' m4 overrides cl1sel2
10544: end-class cl1
10545: 
10546: create obj1 object dict-new drop
10547: create obj2 cl1    dict-new drop
10548: @end example
10549: 
10550: The data structure created by this code (including the data structure
10551: for @code{object}) is shown in the
10552: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10553: @comment TODO add this diagram..
10554: 
10555: @node Objects Glossary,  , Objects Implementation, Objects
10556: @subsubsection @file{objects.fs} Glossary
10557: @cindex @file{objects.fs} Glossary
10558: 
10559: 
10560: doc---objects-bind
10561: doc---objects-<bind>
10562: doc---objects-bind'
10563: doc---objects-[bind]
10564: doc---objects-class
10565: doc---objects-class->map
10566: doc---objects-class-inst-size
10567: doc---objects-class-override!
10568: doc---objects-class-previous
10569: doc---objects-class>order
10570: doc---objects-construct
10571: doc---objects-current'
10572: doc---objects-[current]
10573: doc---objects-current-interface
10574: doc---objects-dict-new
10575: doc---objects-end-class
10576: doc---objects-end-class-noname
10577: doc---objects-end-interface
10578: doc---objects-end-interface-noname
10579: doc---objects-end-methods
10580: doc---objects-exitm
10581: doc---objects-heap-new
10582: doc---objects-implementation
10583: doc---objects-init-object
10584: doc---objects-inst-value
10585: doc---objects-inst-var
10586: doc---objects-interface
10587: doc---objects-m:
10588: doc---objects-:m
10589: doc---objects-;m
10590: doc---objects-method
10591: doc---objects-methods
10592: doc---objects-object
10593: doc---objects-overrides
10594: doc---objects-[parent]
10595: doc---objects-print
10596: doc---objects-protected
10597: doc---objects-public
10598: doc---objects-selector
10599: doc---objects-this
10600: doc---objects-<to-inst>
10601: doc---objects-[to-inst]
10602: doc---objects-to-this
10603: doc---objects-xt-new
10604: 
10605: 
10606: @c -------------------------------------------------------------
10607: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10608: @subsection The @file{oof.fs} model
10609: @cindex oof
10610: @cindex object-oriented programming
10611: 
10612: @cindex @file{objects.fs}
10613: @cindex @file{oof.fs}
10614: 
10615: This section describes the @file{oof.fs} package.
10616: 
10617: The package described in this section has been used in bigFORTH since 1991, and
10618: used for two large applications: a chromatographic system used to
10619: create new medicaments, and a graphic user interface library (MINOS).
10620: 
10621: You can find a description (in German) of @file{oof.fs} in @cite{Object
10622: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10623: 10(2), 1994.
10624: 
10625: @menu
10626: * Properties of the OOF model::  
10627: * Basic OOF Usage::             
10628: * The OOF base class::          
10629: * Class Declaration::           
10630: * Class Implementation::        
10631: @end menu
10632: 
10633: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10634: @subsubsection Properties of the @file{oof.fs} model
10635: @cindex @file{oof.fs} properties
10636: 
10637: @itemize @bullet
10638: @item
10639: This model combines object oriented programming with information
10640: hiding. It helps you writing large application, where scoping is
10641: necessary, because it provides class-oriented scoping.
10642: 
10643: @item
10644: Named objects, object pointers, and object arrays can be created,
10645: selector invocation uses the ``object selector'' syntax. Selector invocation
10646: to objects and/or selectors on the stack is a bit less convenient, but
10647: possible.
10648: 
10649: @item
10650: Selector invocation and instance variable usage of the active object is
10651: straightforward, since both make use of the active object.
10652: 
10653: @item
10654: Late binding is efficient and easy to use.
10655: 
10656: @item
10657: State-smart objects parse selectors. However, extensibility is provided
10658: using a (parsing) selector @code{postpone} and a selector @code{'}.
10659: 
10660: @item
10661: An implementation in ANS Forth is available.
10662: 
10663: @end itemize
10664: 
10665: 
10666: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10667: @subsubsection Basic @file{oof.fs} Usage
10668: @cindex @file{oof.fs} usage
10669: 
10670: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
10671: 
10672: You can define a class for graphical objects like this:
10673: 
10674: @cindex @code{class} usage
10675: @cindex @code{class;} usage
10676: @cindex @code{method} usage
10677: @example
10678: object class graphical \ "object" is the parent class
10679:   method draw ( x y graphical -- )
10680: class;
10681: @end example
10682: 
10683: This code defines a class @code{graphical} with an
10684: operation @code{draw}.  We can perform the operation
10685: @code{draw} on any @code{graphical} object, e.g.:
10686: 
10687: @example
10688: 100 100 t-rex draw
10689: @end example
10690: 
10691: @noindent
10692: where @code{t-rex} is an object or object pointer, created with e.g.
10693: @code{graphical : t-rex}.
10694: 
10695: @cindex abstract class
10696: How do we create a graphical object? With the present definitions,
10697: we cannot create a useful graphical object. The class
10698: @code{graphical} describes graphical objects in general, but not
10699: any concrete graphical object type (C++ users would call it an
10700: @emph{abstract class}); e.g., there is no method for the selector
10701: @code{draw} in the class @code{graphical}.
10702: 
10703: For concrete graphical objects, we define child classes of the
10704: class @code{graphical}, e.g.:
10705: 
10706: @example
10707: graphical class circle \ "graphical" is the parent class
10708:   cell var circle-radius
10709: how:
10710:   : draw ( x y -- )
10711:     circle-radius @@ draw-circle ;
10712: 
10713:   : init ( n-radius -- (
10714:     circle-radius ! ;
10715: class;
10716: @end example
10717: 
10718: Here we define a class @code{circle} as a child of @code{graphical},
10719: with a field @code{circle-radius}; it defines new methods for the
10720: selectors @code{draw} and @code{init} (@code{init} is defined in
10721: @code{object}, the parent class of @code{graphical}).
10722: 
10723: Now we can create a circle in the dictionary with:
10724: 
10725: @example
10726: 50 circle : my-circle
10727: @end example
10728: 
10729: @noindent
10730: @code{:} invokes @code{init}, thus initializing the field
10731: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10732: with:
10733: 
10734: @example
10735: 100 100 my-circle draw
10736: @end example
10737: 
10738: @cindex selector invocation, restrictions
10739: @cindex class definition, restrictions
10740: Note: You can only invoke a selector if the receiving object belongs to
10741: the class where the selector was defined or one of its descendents;
10742: e.g., you can invoke @code{draw} only for objects belonging to
10743: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10744: mechanism will check if you try to invoke a selector that is not
10745: defined in this class hierarchy, so you'll get an error at compilation
10746: time.
10747: 
10748: 
10749: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10750: @subsubsection The @file{oof.fs} base class
10751: @cindex @file{oof.fs} base class
10752: 
10753: When you define a class, you have to specify a parent class.  So how do
10754: you start defining classes? There is one class available from the start:
10755: @code{object}. You have to use it as ancestor for all classes. It is the
10756: only class that has no parent. Classes are also objects, except that
10757: they don't have instance variables; class manipulation such as
10758: inheritance or changing definitions of a class is handled through
10759: selectors of the class @code{object}.
10760: 
10761: @code{object} provides a number of selectors:
10762: 
10763: @itemize @bullet
10764: @item
10765: @code{class} for subclassing, @code{definitions} to add definitions
10766: later on, and @code{class?} to get type informations (is the class a
10767: subclass of the class passed on the stack?).
10768: 
10769: doc---object-class
10770: doc---object-definitions
10771: doc---object-class?
10772: 
10773: 
10774: @item
10775: @code{init} and @code{dispose} as constructor and destructor of the
10776: object. @code{init} is invocated after the object's memory is allocated,
10777: while @code{dispose} also handles deallocation. Thus if you redefine
10778: @code{dispose}, you have to call the parent's dispose with @code{super
10779: dispose}, too.
10780: 
10781: doc---object-init
10782: doc---object-dispose
10783: 
10784: 
10785: @item
10786: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10787: @code{[]} to create named and unnamed objects and object arrays or
10788: object pointers.
10789: 
10790: doc---object-new
10791: doc---object-new[]
10792: doc---object-:
10793: doc---object-ptr
10794: doc---object-asptr
10795: doc---object-[]
10796: 
10797: 
10798: @item
10799: @code{::} and @code{super} for explicit scoping. You should use explicit
10800: scoping only for super classes or classes with the same set of instance
10801: variables. Explicitly-scoped selectors use early binding.
10802: 
10803: doc---object-::
10804: doc---object-super
10805: 
10806: 
10807: @item
10808: @code{self} to get the address of the object
10809: 
10810: doc---object-self
10811: 
10812: 
10813: @item
10814: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10815: pointers and instance defers.
10816: 
10817: doc---object-bind
10818: doc---object-bound
10819: doc---object-link
10820: doc---object-is
10821: 
10822: 
10823: @item
10824: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10825: form the stack, and @code{postpone} to generate selector invocation code.
10826: 
10827: doc---object-'
10828: doc---object-postpone
10829: 
10830: 
10831: @item
10832: @code{with} and @code{endwith} to select the active object from the
10833: stack, and enable its scope. Using @code{with} and @code{endwith}
10834: also allows you to create code using selector @code{postpone} without being
10835: trapped by the state-smart objects.
10836: 
10837: doc---object-with
10838: doc---object-endwith
10839: 
10840: 
10841: @end itemize
10842: 
10843: @node Class Declaration, Class Implementation, The OOF base class, OOF
10844: @subsubsection Class Declaration
10845: @cindex class declaration
10846: 
10847: @itemize @bullet
10848: @item
10849: Instance variables
10850: 
10851: doc---oof-var
10852: 
10853: 
10854: @item
10855: Object pointers
10856: 
10857: doc---oof-ptr
10858: doc---oof-asptr
10859: 
10860: 
10861: @item
10862: Instance defers
10863: 
10864: doc---oof-defer
10865: 
10866: 
10867: @item
10868: Method selectors
10869: 
10870: doc---oof-early
10871: doc---oof-method
10872: 
10873: 
10874: @item
10875: Class-wide variables
10876: 
10877: doc---oof-static
10878: 
10879: 
10880: @item
10881: End declaration
10882: 
10883: doc---oof-how:
10884: doc---oof-class;
10885: 
10886: 
10887: @end itemize
10888: 
10889: @c -------------------------------------------------------------
10890: @node Class Implementation,  , Class Declaration, OOF
10891: @subsubsection Class Implementation
10892: @cindex class implementation
10893: 
10894: @c -------------------------------------------------------------
10895: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10896: @subsection The @file{mini-oof.fs} model
10897: @cindex mini-oof
10898: 
10899: Gforth's third object oriented Forth package is a 12-liner. It uses a
10900: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
10901: and reduces to the bare minimum of features. This is based on a posting
10902: of Bernd Paysan in comp.lang.forth.
10903: 
10904: @menu
10905: * Basic Mini-OOF Usage::        
10906: * Mini-OOF Example::            
10907: * Mini-OOF Implementation::     
10908: @end menu
10909: 
10910: @c -------------------------------------------------------------
10911: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10912: @subsubsection Basic @file{mini-oof.fs} Usage
10913: @cindex mini-oof usage
10914: 
10915: There is a base class (@code{class}, which allocates one cell for the
10916: object pointer) plus seven other words: to define a method, a variable,
10917: a class; to end a class, to resolve binding, to allocate an object and
10918: to compile a class method.
10919: @comment TODO better description of the last one
10920: 
10921: 
10922: doc-object
10923: doc-method
10924: doc-var
10925: doc-class
10926: doc-end-class
10927: doc-defines
10928: doc-new
10929: doc-::
10930: 
10931: 
10932: 
10933: @c -------------------------------------------------------------
10934: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
10935: @subsubsection Mini-OOF Example
10936: @cindex mini-oof example
10937: 
10938: A short example shows how to use this package. This example, in slightly
10939: extended form, is supplied as @file{moof-exm.fs}
10940: @comment TODO could flesh this out with some comments from the Forthwrite article
10941: 
10942: @example
10943: object class
10944:   method init
10945:   method draw
10946: end-class graphical
10947: @end example
10948: 
10949: This code defines a class @code{graphical} with an
10950: operation @code{draw}.  We can perform the operation
10951: @code{draw} on any @code{graphical} object, e.g.:
10952: 
10953: @example
10954: 100 100 t-rex draw
10955: @end example
10956: 
10957: where @code{t-rex} is an object or object pointer, created with e.g.
10958: @code{graphical new Constant t-rex}.
10959: 
10960: For concrete graphical objects, we define child classes of the
10961: class @code{graphical}, e.g.:
10962: 
10963: @example
10964: graphical class
10965:   cell var circle-radius
10966: end-class circle \ "graphical" is the parent class
10967: 
10968: :noname ( x y -- )
10969:   circle-radius @@ draw-circle ; circle defines draw
10970: :noname ( r -- )
10971:   circle-radius ! ; circle defines init
10972: @end example
10973: 
10974: There is no implicit init method, so we have to define one. The creation
10975: code of the object now has to call init explicitely.
10976: 
10977: @example
10978: circle new Constant my-circle
10979: 50 my-circle init
10980: @end example
10981: 
10982: It is also possible to add a function to create named objects with
10983: automatic call of @code{init}, given that all objects have @code{init}
10984: on the same place:
10985: 
10986: @example
10987: : new: ( .. o "name" -- )
10988:     new dup Constant init ;
10989: 80 circle new: large-circle
10990: @end example
10991: 
10992: We can draw this new circle at (100,100) with:
10993: 
10994: @example
10995: 100 100 my-circle draw
10996: @end example
10997: 
10998: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
10999: @subsubsection @file{mini-oof.fs} Implementation
11000: 
11001: Object-oriented systems with late binding typically use a
11002: ``vtable''-approach: the first variable in each object is a pointer to a
11003: table, which contains the methods as function pointers. The vtable
11004: may also contain other information.
11005: 
11006: So first, let's declare selectors:
11007: 
11008: @example
11009: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11010:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11011: @end example
11012: 
11013: During selector declaration, the number of selectors and instance
11014: variables is on the stack (in address units). @code{method} creates one
11015: selector and increments the selector number. To execute a selector, it
11016: takes the object, fetches the vtable pointer, adds the offset, and
11017: executes the method @i{xt} stored there. Each selector takes the object
11018: it is invoked with as top of stack parameter; it passes the parameters
11019: (including the object) unchanged to the appropriate method which should
11020: consume that object.
11021: 
11022: Now, we also have to declare instance variables
11023: 
11024: @example
11025: : var ( m v size "name" -- m v' ) Create  over , +
11026:   DOES> ( o -- addr ) @@ + ;
11027: @end example
11028: 
11029: As before, a word is created with the current offset. Instance
11030: variables can have different sizes (cells, floats, doubles, chars), so
11031: all we do is take the size and add it to the offset. If your machine
11032: has alignment restrictions, put the proper @code{aligned} or
11033: @code{faligned} before the variable, to adjust the variable
11034: offset. That's why it is on the top of stack.
11035: 
11036: We need a starting point (the base object) and some syntactic sugar:
11037: 
11038: @example
11039: Create object  1 cells , 2 cells ,
11040: : class ( class -- class selectors vars ) dup 2@@ ;
11041: @end example
11042: 
11043: For inheritance, the vtable of the parent object has to be
11044: copied when a new, derived class is declared. This gives all the
11045: methods of the parent class, which can be overridden, though.
11046: 
11047: @example
11048: : end-class  ( class selectors vars "name" -- )
11049:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11050:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11051: @end example
11052: 
11053: The first line creates the vtable, initialized with
11054: @code{noop}s. The second line is the inheritance mechanism, it
11055: copies the xts from the parent vtable.
11056: 
11057: We still have no way to define new methods, let's do that now:
11058: 
11059: @example
11060: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11061: @end example
11062: 
11063: To allocate a new object, we need a word, too:
11064: 
11065: @example
11066: : new ( class -- o )  here over @@ allot swap over ! ;
11067: @end example
11068: 
11069: Sometimes derived classes want to access the method of the
11070: parent object. There are two ways to achieve this with Mini-OOF:
11071: first, you could use named words, and second, you could look up the
11072: vtable of the parent object.
11073: 
11074: @example
11075: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11076: @end example
11077: 
11078: 
11079: Nothing can be more confusing than a good example, so here is
11080: one. First let's declare a text object (called
11081: @code{button}), that stores text and position:
11082: 
11083: @example
11084: object class
11085:   cell var text
11086:   cell var len
11087:   cell var x
11088:   cell var y
11089:   method init
11090:   method draw
11091: end-class button
11092: @end example
11093: 
11094: @noindent
11095: Now, implement the two methods, @code{draw} and @code{init}:
11096: 
11097: @example
11098: :noname ( o -- )
11099:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11100:  button defines draw
11101: :noname ( addr u o -- )
11102:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11103:  button defines init
11104: @end example
11105: 
11106: @noindent
11107: To demonstrate inheritance, we define a class @code{bold-button}, with no
11108: new data and no new selectors:
11109: 
11110: @example
11111: button class
11112: end-class bold-button
11113: 
11114: : bold   27 emit ." [1m" ;
11115: : normal 27 emit ." [0m" ;
11116: @end example
11117: 
11118: @noindent
11119: The class @code{bold-button} has a different draw method to
11120: @code{button}, but the new method is defined in terms of the draw method
11121: for @code{button}:
11122: 
11123: @example
11124: :noname bold [ button :: draw ] normal ; bold-button defines draw
11125: @end example
11126: 
11127: @noindent
11128: Finally, create two objects and apply selectors:
11129: 
11130: @example
11131: button new Constant foo
11132: s" thin foo" foo init
11133: page
11134: foo draw
11135: bold-button new Constant bar
11136: s" fat bar" bar init
11137: 1 bar y !
11138: bar draw
11139: @end example
11140: 
11141: 
11142: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11143: @subsection Comparison with other object models
11144: @cindex comparison of object models
11145: @cindex object models, comparison
11146: 
11147: Many object-oriented Forth extensions have been proposed (@cite{A survey
11148: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11149: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11150: relation of the object models described here to two well-known and two
11151: closely-related (by the use of method maps) models.  Andras Zsoter
11152: helped us with this section.
11153: 
11154: @cindex Neon model
11155: The most popular model currently seems to be the Neon model (see
11156: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11157: 1997) by Andrew McKewan) but this model has a number of limitations
11158: @footnote{A longer version of this critique can be
11159: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11160: Dimensions, May 1997) by Anton Ertl.}:
11161: 
11162: @itemize @bullet
11163: @item
11164: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11165: to pass objects on the stack.
11166: 
11167: @item
11168: It requires that the selector parses the input stream (at
11169: compile time); this leads to reduced extensibility and to bugs that are
11170: hard to find.
11171: 
11172: @item
11173: It allows using every selector on every object; this eliminates the
11174: need for interfaces, but makes it harder to create efficient
11175: implementations.
11176: @end itemize
11177: 
11178: @cindex Pountain's object-oriented model
11179: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11180: Press, London, 1987) by Dick Pountain. However, it is not really about
11181: object-oriented programming, because it hardly deals with late
11182: binding. Instead, it focuses on features like information hiding and
11183: overloading that are characteristic of modular languages like Ada (83).
11184: 
11185: @cindex Zsoter's object-oriented model
11186: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11187: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11188: describes a model that makes heavy use of an active object (like
11189: @code{this} in @file{objects.fs}): The active object is not only used
11190: for accessing all fields, but also specifies the receiving object of
11191: every selector invocation; you have to change the active object
11192: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11193: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11194: the method entry point is unnecessary with Zsoter's model, because the
11195: receiving object is the active object already. On the other hand, the
11196: explicit change is absolutely necessary in that model, because otherwise
11197: no one could ever change the active object. An ANS Forth implementation
11198: of this model is available through
11199: @uref{http://www.forth.org/oopf.html}.
11200: 
11201: @cindex @file{oof.fs}, differences to other models
11202: The @file{oof.fs} model combines information hiding and overloading
11203: resolution (by keeping names in various word lists) with object-oriented
11204: programming. It sets the active object implicitly on method entry, but
11205: also allows explicit changing (with @code{>o...o>} or with
11206: @code{with...endwith}). It uses parsing and state-smart objects and
11207: classes for resolving overloading and for early binding: the object or
11208: class parses the selector and determines the method from this. If the
11209: selector is not parsed by an object or class, it performs a call to the
11210: selector for the active object (late binding), like Zsoter's model.
11211: Fields are always accessed through the active object. The big
11212: disadvantage of this model is the parsing and the state-smartness, which
11213: reduces extensibility and increases the opportunities for subtle bugs;
11214: essentially, you are only safe if you never tick or @code{postpone} an
11215: object or class (Bernd disagrees, but I (Anton) am not convinced).
11216: 
11217: @cindex @file{mini-oof.fs}, differences to other models
11218: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11219: version of the @file{objects.fs} model, but syntactically it is a
11220: mixture of the @file{objects.fs} and @file{oof.fs} models.
11221: 
11222: 
11223: @c -------------------------------------------------------------
11224: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11225: @section Programming Tools
11226: @cindex programming tools
11227: 
11228: @c !! move this and assembler down below OO stuff.
11229: 
11230: @menu
11231: * Examining::                   
11232: * Forgetting words::            
11233: * Debugging::                   Simple and quick.
11234: * Assertions::                  Making your programs self-checking.
11235: * Singlestep Debugger::         Executing your program word by word.
11236: @end menu
11237: 
11238: @node Examining, Forgetting words, Programming Tools, Programming Tools
11239: @subsection Examining data and code
11240: @cindex examining data and code
11241: @cindex data examination
11242: @cindex code examination
11243: 
11244: The following words inspect the stack non-destructively:
11245: 
11246: doc-.s
11247: doc-f.s
11248: 
11249: There is a word @code{.r} but it does @i{not} display the return stack!
11250: It is used for formatted numeric output (@pxref{Simple numeric output}).
11251: 
11252: doc-depth
11253: doc-fdepth
11254: doc-clearstack
11255: 
11256: The following words inspect memory.
11257: 
11258: doc-?
11259: doc-dump
11260: 
11261: And finally, @code{see} allows to inspect code:
11262: 
11263: doc-see
11264: doc-xt-see
11265: doc-simple-see
11266: doc-simple-see-range
11267: 
11268: @node Forgetting words, Debugging, Examining, Programming Tools
11269: @subsection Forgetting words
11270: @cindex words, forgetting
11271: @cindex forgeting words
11272: 
11273: @c  anton: other, maybe better places for this subsection: Defining Words;
11274: @c  Dictionary allocation.  At least a reference should be there.
11275: 
11276: Forth allows you to forget words (and everything that was alloted in the
11277: dictonary after them) in a LIFO manner.
11278: 
11279: doc-marker
11280: 
11281: The most common use of this feature is during progam development: when
11282: you change a source file, forget all the words it defined and load it
11283: again (since you also forget everything defined after the source file
11284: was loaded, you have to reload that, too).  Note that effects like
11285: storing to variables and destroyed system words are not undone when you
11286: forget words.  With a system like Gforth, that is fast enough at
11287: starting up and compiling, I find it more convenient to exit and restart
11288: Gforth, as this gives me a clean slate.
11289: 
11290: Here's an example of using @code{marker} at the start of a source file
11291: that you are debugging; it ensures that you only ever have one copy of
11292: the file's definitions compiled at any time:
11293: 
11294: @example
11295: [IFDEF] my-code
11296:     my-code
11297: [ENDIF]
11298: 
11299: marker my-code
11300: init-included-files
11301: 
11302: \ .. definitions start here
11303: \ .
11304: \ .
11305: \ end
11306: @end example
11307: 
11308: 
11309: @node Debugging, Assertions, Forgetting words, Programming Tools
11310: @subsection Debugging
11311: @cindex debugging
11312: 
11313: Languages with a slow edit/compile/link/test development loop tend to
11314: require sophisticated tracing/stepping debuggers to facilate debugging.
11315: 
11316: A much better (faster) way in fast-compiling languages is to add
11317: printing code at well-selected places, let the program run, look at
11318: the output, see where things went wrong, add more printing code, etc.,
11319: until the bug is found.
11320: 
11321: The simple debugging aids provided in @file{debugs.fs}
11322: are meant to support this style of debugging.
11323: 
11324: The word @code{~~} prints debugging information (by default the source
11325: location and the stack contents). It is easy to insert. If you use Emacs
11326: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11327: query-replace them with nothing). The deferred words
11328: @code{printdebugdata} and @code{.debugline} control the output of
11329: @code{~~}. The default source location output format works well with
11330: Emacs' compilation mode, so you can step through the program at the
11331: source level using @kbd{C-x `} (the advantage over a stepping debugger
11332: is that you can step in any direction and you know where the crash has
11333: happened or where the strange data has occurred).
11334: 
11335: doc-~~
11336: doc-printdebugdata
11337: doc-.debugline
11338: 
11339: @cindex filenames in @code{~~} output
11340: @code{~~} (and assertions) will usually print the wrong file name if a
11341: marker is executed in the same file after their occurance.  They will
11342: print @samp{*somewhere*} as file name if a marker is executed in the
11343: same file before their occurance.
11344: 
11345: 
11346: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11347: @subsection Assertions
11348: @cindex assertions
11349: 
11350: It is a good idea to make your programs self-checking, especially if you
11351: make an assumption that may become invalid during maintenance (for
11352: example, that a certain field of a data structure is never zero). Gforth
11353: supports @dfn{assertions} for this purpose. They are used like this:
11354: 
11355: @example
11356: assert( @i{flag} )
11357: @end example
11358: 
11359: The code between @code{assert(} and @code{)} should compute a flag, that
11360: should be true if everything is alright and false otherwise. It should
11361: not change anything else on the stack. The overall stack effect of the
11362: assertion is @code{( -- )}. E.g.
11363: 
11364: @example
11365: assert( 1 1 + 2 = ) \ what we learn in school
11366: assert( dup 0<> ) \ assert that the top of stack is not zero
11367: assert( false ) \ this code should not be reached
11368: @end example
11369: 
11370: The need for assertions is different at different times. During
11371: debugging, we want more checking, in production we sometimes care more
11372: for speed. Therefore, assertions can be turned off, i.e., the assertion
11373: becomes a comment. Depending on the importance of an assertion and the
11374: time it takes to check it, you may want to turn off some assertions and
11375: keep others turned on. Gforth provides several levels of assertions for
11376: this purpose:
11377: 
11378: 
11379: doc-assert0(
11380: doc-assert1(
11381: doc-assert2(
11382: doc-assert3(
11383: doc-assert(
11384: doc-)
11385: 
11386: 
11387: The variable @code{assert-level} specifies the highest assertions that
11388: are turned on. I.e., at the default @code{assert-level} of one,
11389: @code{assert0(} and @code{assert1(} assertions perform checking, while
11390: @code{assert2(} and @code{assert3(} assertions are treated as comments.
11391: 
11392: The value of @code{assert-level} is evaluated at compile-time, not at
11393: run-time. Therefore you cannot turn assertions on or off at run-time;
11394: you have to set the @code{assert-level} appropriately before compiling a
11395: piece of code. You can compile different pieces of code at different
11396: @code{assert-level}s (e.g., a trusted library at level 1 and
11397: newly-written code at level 3).
11398: 
11399: 
11400: doc-assert-level
11401: 
11402: 
11403: If an assertion fails, a message compatible with Emacs' compilation mode
11404: is produced and the execution is aborted (currently with @code{ABORT"}.
11405: If there is interest, we will introduce a special throw code. But if you
11406: intend to @code{catch} a specific condition, using @code{throw} is
11407: probably more appropriate than an assertion).
11408: 
11409: @cindex filenames in assertion output
11410: Assertions (and @code{~~}) will usually print the wrong file name if a
11411: marker is executed in the same file after their occurance.  They will
11412: print @samp{*somewhere*} as file name if a marker is executed in the
11413: same file before their occurance.
11414: 
11415: Definitions in ANS Forth for these assertion words are provided
11416: in @file{compat/assert.fs}.
11417: 
11418: 
11419: @node Singlestep Debugger,  , Assertions, Programming Tools
11420: @subsection Singlestep Debugger
11421: @cindex singlestep Debugger
11422: @cindex debugging Singlestep
11423: 
11424: The singlestep debugger does not work in this release.
11425: 
11426: When you create a new word there's often the need to check whether it
11427: behaves correctly or not. You can do this by typing @code{dbg
11428: badword}. A debug session might look like this:
11429: 
11430: @example
11431: : badword 0 DO i . LOOP ;  ok
11432: 2 dbg badword 
11433: : badword  
11434: Scanning code...
11435: 
11436: Nesting debugger ready!
11437: 
11438: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
11439: 400D4740  8049F68 DO             -> [ 0 ] 
11440: 400D4744  804A0C8 i              -> [ 1 ] 00000 
11441: 400D4748 400C5E60 .              -> 0 [ 0 ] 
11442: 400D474C  8049D0C LOOP           -> [ 0 ] 
11443: 400D4744  804A0C8 i              -> [ 1 ] 00001 
11444: 400D4748 400C5E60 .              -> 1 [ 0 ] 
11445: 400D474C  8049D0C LOOP           -> [ 0 ] 
11446: 400D4758  804B384 ;              ->  ok
11447: @end example
11448: 
11449: Each line displayed is one step. You always have to hit return to
11450: execute the next word that is displayed. If you don't want to execute
11451: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11452: an overview what keys are available:
11453: 
11454: @table @i
11455: 
11456: @item @key{RET}
11457: Next; Execute the next word.
11458: 
11459: @item n
11460: Nest; Single step through next word.
11461: 
11462: @item u
11463: Unnest; Stop debugging and execute rest of word. If we got to this word
11464: with nest, continue debugging with the calling word.
11465: 
11466: @item d
11467: Done; Stop debugging and execute rest.
11468: 
11469: @item s
11470: Stop; Abort immediately.
11471: 
11472: @end table
11473: 
11474: Debugging large application with this mechanism is very difficult, because
11475: you have to nest very deeply into the program before the interesting part
11476: begins. This takes a lot of time. 
11477: 
11478: To do it more directly put a @code{BREAK:} command into your source code.
11479: When program execution reaches @code{BREAK:} the single step debugger is
11480: invoked and you have all the features described above.
11481: 
11482: If you have more than one part to debug it is useful to know where the
11483: program has stopped at the moment. You can do this by the 
11484: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11485: string is typed out when the ``breakpoint'' is reached.
11486: 
11487: 
11488: doc-dbg
11489: doc-break:
11490: doc-break"
11491: 
11492: 
11493: 
11494: @c -------------------------------------------------------------
11495: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11496: @section Assembler and Code Words
11497: @cindex assembler
11498: @cindex code words
11499: 
11500: @menu
11501: * Code and ;code::              
11502: * Common Assembler::            Assembler Syntax
11503: * Common Disassembler::         
11504: * 386 Assembler::               Deviations and special cases
11505: * Alpha Assembler::             Deviations and special cases
11506: * MIPS assembler::              Deviations and special cases
11507: * Other assemblers::            How to write them
11508: @end menu
11509: 
11510: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11511: @subsection @code{Code} and @code{;code}
11512: 
11513: Gforth provides some words for defining primitives (words written in
11514: machine code), and for defining the machine-code equivalent of
11515: @code{DOES>}-based defining words. However, the machine-independent
11516: nature of Gforth poses a few problems: First of all, Gforth runs on
11517: several architectures, so it can provide no standard assembler. What's
11518: worse is that the register allocation not only depends on the processor,
11519: but also on the @code{gcc} version and options used.
11520: 
11521: The words that Gforth offers encapsulate some system dependences (e.g.,
11522: the header structure), so a system-independent assembler may be used in
11523: Gforth. If you do not have an assembler, you can compile machine code
11524: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11525: because these words emit stuff in @i{data} space; it works because
11526: Gforth has unified code/data spaces. Assembler isn't likely to be
11527: portable anyway.}.
11528: 
11529: 
11530: doc-assembler
11531: doc-init-asm
11532: doc-code
11533: doc-end-code
11534: doc-;code
11535: doc-flush-icache
11536: 
11537: 
11538: If @code{flush-icache} does not work correctly, @code{code} words
11539: etc. will not work (reliably), either.
11540: 
11541: The typical usage of these @code{code} words can be shown most easily by
11542: analogy to the equivalent high-level defining words:
11543: 
11544: @example
11545: : foo                              code foo
11546:    <high-level Forth words>              <assembler>
11547: ;                                  end-code
11548:                                 
11549: : bar                              : bar
11550:    <high-level Forth words>           <high-level Forth words>
11551:    CREATE                             CREATE
11552:       <high-level Forth words>           <high-level Forth words>
11553:    DOES>                              ;code
11554:       <high-level Forth words>           <assembler>
11555: ;                                  end-code
11556: @end example
11557: 
11558: @c anton: the following stuff is also in "Common Assembler", in less detail.
11559: 
11560: @cindex registers of the inner interpreter
11561: In the assembly code you will want to refer to the inner interpreter's
11562: registers (e.g., the data stack pointer) and you may want to use other
11563: registers for temporary storage. Unfortunately, the register allocation
11564: is installation-dependent.
11565: 
11566: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
11567: (return stack pointer) may be in different places in @code{gforth} and
11568: @code{gforth-fast}, or different installations.  This means that you
11569: cannot write a @code{NEXT} routine that works reliably on both versions
11570: or different installations; so for doing @code{NEXT}, I recommend
11571: jumping to @code{' noop >code-address}, which contains nothing but a
11572: @code{NEXT}.
11573: 
11574: For general accesses to the inner interpreter's registers, the easiest
11575: solution is to use explicit register declarations (@pxref{Explicit Reg
11576: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11577: all of the inner interpreter's registers: You have to compile Gforth
11578: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11579: the appropriate declarations must be present in the @code{machine.h}
11580: file (see @code{mips.h} for an example; you can find a full list of all
11581: declarable register symbols with @code{grep register engine.c}). If you
11582: give explicit registers to all variables that are declared at the
11583: beginning of @code{engine()}, you should be able to use the other
11584: caller-saved registers for temporary storage. Alternatively, you can use
11585: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11586: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11587: reserve a register (however, this restriction on register allocation may
11588: slow Gforth significantly).
11589: 
11590: If this solution is not viable (e.g., because @code{gcc} does not allow
11591: you to explicitly declare all the registers you need), you have to find
11592: out by looking at the code where the inner interpreter's registers
11593: reside and which registers can be used for temporary storage. You can
11594: get an assembly listing of the engine's code with @code{make engine.s}.
11595: 
11596: In any case, it is good practice to abstract your assembly code from the
11597: actual register allocation. E.g., if the data stack pointer resides in
11598: register @code{$17}, create an alias for this register called @code{sp},
11599: and use that in your assembly code.
11600: 
11601: @cindex code words, portable
11602: Another option for implementing normal and defining words efficiently
11603: is to add the desired functionality to the source of Gforth. For normal
11604: words you just have to edit @file{primitives} (@pxref{Automatic
11605: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11606: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11607: @file{prims2x.fs}, and possibly @file{cross.fs}.
11608: 
11609: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11610: @subsection Common Assembler
11611: 
11612: The assemblers in Gforth generally use a postfix syntax, i.e., the
11613: instruction name follows the operands.
11614: 
11615: The operands are passed in the usual order (the same that is used in the
11616: manual of the architecture).  Since they all are Forth words, they have
11617: to be separated by spaces; you can also use Forth words to compute the
11618: operands.
11619: 
11620: The instruction names usually end with a @code{,}.  This makes it easier
11621: to visually separate instructions if you put several of them on one
11622: line; it also avoids shadowing other Forth words (e.g., @code{and}).
11623: 
11624: Registers are usually specified by number; e.g., (decimal) @code{11}
11625: specifies registers R11 and F11 on the Alpha architecture (which one,
11626: depends on the instruction).  The usual names are also available, e.g.,
11627: @code{s2} for R11 on Alpha.
11628: 
11629: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11630: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11631: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11632: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
11633: conditions are specified in a way specific to each assembler.
11634: 
11635: Note that the register assignments of the Gforth engine can change
11636: between Gforth versions, or even between different compilations of the
11637: same Gforth version (e.g., if you use a different GCC version).  So if
11638: you want to refer to Gforth's registers (e.g., the stack pointer or
11639: TOS), I recommend defining your own words for refering to these
11640: registers, and using them later on; then you can easily adapt to a
11641: changed register assignment.  The stability of the register assignment
11642: is usually better if you build Gforth with @code{--enable-force-reg}.
11643: 
11644: The most common use of these registers is to dispatch to the next word
11645: (the @code{next} routine).  A portable way to do this is to jump to
11646: @code{' noop >code-address} (of course, this is less efficient than
11647: integrating the @code{next} code and scheduling it well).
11648: 
11649: Another difference between Gforth version is that the top of stack is
11650: kept in memory in @code{gforth} and, on most platforms, in a register in
11651: @code{gforth-fast}.
11652: 
11653: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11654: @subsection Common Disassembler
11655: 
11656: You can disassemble a @code{code} word with @code{see}
11657: (@pxref{Debugging}).  You can disassemble a section of memory with
11658: 
11659: doc-disasm
11660: 
11661: The disassembler generally produces output that can be fed into the
11662: assembler (i.e., same syntax, etc.).  It also includes additional
11663: information in comments.  In particular, the address of the instruction
11664: is given in a comment before the instruction.
11665: 
11666: @code{See} may display more or less than the actual code of the word,
11667: because the recognition of the end of the code is unreliable.  You can
11668: use @code{disasm} if it did not display enough.  It may display more, if
11669: the code word is not immediately followed by a named word.  If you have
11670: something else there, you can follow the word with @code{align latest ,}
11671: to ensure that the end is recognized.
11672: 
11673: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11674: @subsection 386 Assembler
11675: 
11676: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11677: available under GPL, and originally part of bigFORTH.
11678: 
11679: The 386 disassembler included in Gforth was written by Andrew McKewan
11680: and is in the public domain.
11681: 
11682: The disassembler displays code in an Intel-like prefix syntax.
11683: 
11684: The assembler uses a postfix syntax with reversed parameters.
11685: 
11686: The assembler includes all instruction of the Athlon, i.e. 486 core
11687: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11688: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11689: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
11690: 
11691: There are several prefixes to switch between different operation sizes,
11692: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11693: double-word accesses. Addressing modes can be switched with @code{.wa}
11694: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11695: need a prefix for byte register names (@code{AL} et al).
11696: 
11697: For floating point operations, the prefixes are @code{.fs} (IEEE
11698: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11699: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
11700: 
11701: The MMX opcodes don't have size prefixes, they are spelled out like in
11702: the Intel assembler. Instead of move from and to memory, there are
11703: PLDQ/PLDD and PSTQ/PSTD.
11704: 
11705: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11706: ax.  Immediate values are indicated by postfixing them with @code{#},
11707: e.g., @code{3 #}.  Here are some examples of addressing modes in various
11708: syntaxes:
11709: 
11710: @example
11711: Gforth          Intel (NASM)   AT&T (gas)      Name
11712: .w ax           ax             %ax             register (16 bit)
11713: ax              eax            %eax            register (32 bit)
11714: 3 #             offset 3       $3              immediate
11715: 1000 #)         byte ptr 1000  1000            displacement
11716: bx )            [ebx]          (%ebx)          base
11717: 100 di d)       100[edi]       100(%edi)       base+displacement
11718: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
11719: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
11720: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
11721: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11722: @end example
11723: 
11724: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11725: @code{DI)} to enforce 32-bit displacement fields (useful for
11726: later patching).
11727: 
11728: Some example of instructions are:
11729: 
11730: @example
11731: ax bx mov             \ move ebx,eax
11732: 3 # ax mov            \ mov eax,3
11733: 100 di ) ax mov       \ mov eax,100[edi]
11734: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
11735: .w ax bx mov          \ mov bx,ax
11736: @end example
11737: 
11738: The following forms are supported for binary instructions:
11739: 
11740: @example
11741: <reg> <reg> <inst>
11742: <n> # <reg> <inst>
11743: <mem> <reg> <inst>
11744: <reg> <mem> <inst>
11745: @end example
11746: 
11747: Immediate to memory is not supported.  The shift/rotate syntax is:
11748: 
11749: @example
11750: <reg/mem> 1 # shl \ shortens to shift without immediate
11751: <reg/mem> 4 # shl
11752: <reg/mem> cl shl
11753: @end example
11754: 
11755: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11756: the byte version.
11757: 
11758: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11759: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11760: pc < >= <= >}. (Note that most of these words shadow some Forth words
11761: when @code{assembler} is in front of @code{forth} in the search path,
11762: e.g., in @code{code} words).  Currently the control structure words use
11763: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11764: to shuffle them (you can also use @code{swap} etc.).
11765: 
11766: Here is an example of a @code{code} word (assumes that the stack pointer
11767: is in esi and the TOS is in ebx):
11768: 
11769: @example
11770: code my+ ( n1 n2 -- n )
11771:     4 si D) bx add
11772:     4 # si add
11773:     Next
11774: end-code
11775: @end example
11776: 
11777: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11778: @subsection Alpha Assembler
11779: 
11780: The Alpha assembler and disassembler were originally written by Bernd
11781: Thallner.
11782: 
11783: The register names @code{a0}--@code{a5} are not available to avoid
11784: shadowing hex numbers.
11785: 
11786: Immediate forms of arithmetic instructions are distinguished by a
11787: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11788: does not count as arithmetic instruction).
11789: 
11790: You have to specify all operands to an instruction, even those that
11791: other assemblers consider optional, e.g., the destination register for
11792: @code{br,}, or the destination register and hint for @code{jmp,}.
11793: 
11794: You can specify conditions for @code{if,} by removing the first @code{b}
11795: and the trailing @code{,} from a branch with a corresponding name; e.g.,
11796: 
11797: @example
11798: 11 fgt if, \ if F11>0e
11799:   ...
11800: endif,
11801: @end example
11802: 
11803: @code{fbgt,} gives @code{fgt}.  
11804: 
11805: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11806: @subsection MIPS assembler
11807: 
11808: The MIPS assembler was originally written by Christian Pirker.
11809: 
11810: Currently the assembler and disassembler only cover the MIPS-I
11811: architecture (R3000), and don't support FP instructions.
11812: 
11813: The register names @code{$a0}--@code{$a3} are not available to avoid
11814: shadowing hex numbers.
11815: 
11816: Because there is no way to distinguish registers from immediate values,
11817: you have to explicitly use the immediate forms of instructions, i.e.,
11818: @code{addiu,}, not just @code{addu,} (@command{as} does this
11819: implicitly).
11820: 
11821: If the architecture manual specifies several formats for the instruction
11822: (e.g., for @code{jalr,}), you usually have to use the one with more
11823: arguments (i.e., two for @code{jalr,}).  When in doubt, see
11824: @code{arch/mips/testasm.fs} for an example of correct use.
11825: 
11826: Branches and jumps in the MIPS architecture have a delay slot.  You have
11827: to fill it yourself (the simplest way is to use @code{nop,}), the
11828: assembler does not do it for you (unlike @command{as}).  Even
11829: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11830: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
11831: and @code{then,} just specify branch targets, they are not affected.
11832: 
11833: Note that you must not put branches, jumps, or @code{li,} into the delay
11834: slot: @code{li,} may expand to several instructions, and control flow
11835: instructions may not be put into the branch delay slot in any case.
11836: 
11837: For branches the argument specifying the target is a relative address;
11838: You have to add the address of the delay slot to get the absolute
11839: address.
11840: 
11841: The MIPS architecture also has load delay slots and restrictions on
11842: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11843: yourself to satisfy these restrictions, the assembler does not do it for
11844: you.
11845: 
11846: You can specify the conditions for @code{if,} etc. by taking a
11847: conditional branch and leaving away the @code{b} at the start and the
11848: @code{,} at the end.  E.g.,
11849: 
11850: @example
11851: 4 5 eq if,
11852:   ... \ do something if $4 equals $5
11853: then,
11854: @end example
11855: 
11856: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
11857: @subsection Other assemblers
11858: 
11859: If you want to contribute another assembler/disassembler, please contact
11860: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
11861: an assembler already.  If you are writing them from scratch, please use
11862: a similar syntax style as the one we use (i.e., postfix, commas at the
11863: end of the instruction names, @pxref{Common Assembler}); make the output
11864: of the disassembler be valid input for the assembler, and keep the style
11865: similar to the style we used.
11866: 
11867: Hints on implementation: The most important part is to have a good test
11868: suite that contains all instructions.  Once you have that, the rest is
11869: easy.  For actual coding you can take a look at
11870: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11871: the assembler and disassembler, avoiding redundancy and some potential
11872: bugs.  You can also look at that file (and @pxref{Advanced does> usage
11873: example}) to get ideas how to factor a disassembler.
11874: 
11875: Start with the disassembler, because it's easier to reuse data from the
11876: disassembler for the assembler than the other way round.
11877: 
11878: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11879: how simple it can be.
11880: 
11881: @c -------------------------------------------------------------
11882: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11883: @section Threading Words
11884: @cindex threading words
11885: 
11886: @cindex code address
11887: These words provide access to code addresses and other threading stuff
11888: in Gforth (and, possibly, other interpretive Forths). It more or less
11889: abstracts away the differences between direct and indirect threading
11890: (and, for direct threading, the machine dependences). However, at
11891: present this wordset is still incomplete. It is also pretty low-level;
11892: some day it will hopefully be made unnecessary by an internals wordset
11893: that abstracts implementation details away completely.
11894: 
11895: The terminology used here stems from indirect threaded Forth systems; in
11896: such a system, the XT of a word is represented by the CFA (code field
11897: address) of a word; the CFA points to a cell that contains the code
11898: address.  The code address is the address of some machine code that
11899: performs the run-time action of invoking the word (e.g., the
11900: @code{dovar:} routine pushes the address of the body of the word (a
11901: variable) on the stack
11902: ).
11903: 
11904: @cindex code address
11905: @cindex code field address
11906: In an indirect threaded Forth, you can get the code address of @i{name}
11907: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
11908: >code-address}, independent of the threading method.
11909: 
11910: doc-threading-method
11911: doc->code-address
11912: doc-code-address!
11913: 
11914: @cindex @code{does>}-handler
11915: @cindex @code{does>}-code
11916: For a word defined with @code{DOES>}, the code address usually points to
11917: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
11918: routine (in Gforth on some platforms, it can also point to the dodoes
11919: routine itself).  What you are typically interested in, though, is
11920: whether a word is a @code{DOES>}-defined word, and what Forth code it
11921: executes; @code{>does-code} tells you that.
11922: 
11923: doc->does-code
11924: 
11925: To create a @code{DOES>}-defined word with the following basic words,
11926: you have to set up a @code{DOES>}-handler with @code{does-handler!};
11927: @code{/does-handler} aus behind you have to place your executable Forth
11928: code.  Finally you have to create a word and modify its behaviour with
11929: @code{does-handler!}.
11930: 
11931: doc-does-code!
11932: doc-does-handler!
11933: doc-/does-handler
11934: 
11935: The code addresses produced by various defining words are produced by
11936: the following words:
11937: 
11938: doc-docol:
11939: doc-docon:
11940: doc-dovar:
11941: doc-douser:
11942: doc-dodefer:
11943: doc-dofield:
11944: 
11945: @cindex definer
11946: The following two words generalize @code{>code-address},
11947: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
11948: 
11949: doc->definer
11950: doc-definer!
11951: 
11952: @c -------------------------------------------------------------
11953: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
11954: @section Passing Commands to the Operating System
11955: @cindex operating system - passing commands
11956: @cindex shell commands
11957: 
11958: Gforth allows you to pass an arbitrary string to the host operating
11959: system shell (if such a thing exists) for execution.
11960: 
11961: 
11962: doc-sh
11963: doc-system
11964: doc-$?
11965: doc-getenv
11966: 
11967: 
11968: @c -------------------------------------------------------------
11969: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
11970: @section Keeping track of Time
11971: @cindex time-related words
11972: 
11973: doc-ms
11974: doc-time&date
11975: doc-utime
11976: doc-cputime
11977: 
11978: 
11979: @c -------------------------------------------------------------
11980: @node Miscellaneous Words,  , Keeping track of Time, Words
11981: @section Miscellaneous Words
11982: @cindex miscellaneous words
11983: 
11984: @comment TODO find homes for these
11985: 
11986: These section lists the ANS Forth words that are not documented
11987: elsewhere in this manual. Ultimately, they all need proper homes.
11988: 
11989: doc-quit
11990: 
11991: The following ANS Forth words are not currently supported by Gforth 
11992: (@pxref{ANS conformance}):
11993: 
11994: @code{EDITOR} 
11995: @code{EMIT?} 
11996: @code{FORGET} 
11997: 
11998: @c ******************************************************************
11999: @node Error messages, Tools, Words, Top
12000: @chapter Error messages
12001: @cindex error messages
12002: @cindex backtrace
12003: 
12004: A typical Gforth error message looks like this:
12005: 
12006: @example
12007: in file included from \evaluated string/:-1
12008: in file included from ./yyy.fs:1
12009: ./xxx.fs:4: Invalid memory address
12010: bar
12011: ^^^
12012: Backtrace:
12013: $400E664C @@
12014: $400E6664 foo
12015: @end example
12016: 
12017: The message identifying the error is @code{Invalid memory address}.  The
12018: error happened when text-interpreting line 4 of the file
12019: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12020: word on the line where the error happened, is pointed out (with
12021: @code{^^^}).
12022: 
12023: The file containing the error was included in line 1 of @file{./yyy.fs},
12024: and @file{yyy.fs} was included from a non-file (in this case, by giving
12025: @file{yyy.fs} as command-line parameter to Gforth).
12026: 
12027: At the end of the error message you find a return stack dump that can be
12028: interpreted as a backtrace (possibly empty). On top you find the top of
12029: the return stack when the @code{throw} happened, and at the bottom you
12030: find the return stack entry just above the return stack of the topmost
12031: text interpreter.
12032: 
12033: To the right of most return stack entries you see a guess for the word
12034: that pushed that return stack entry as its return address. This gives a
12035: backtrace. In our case we see that @code{bar} called @code{foo}, and
12036: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12037: address} exception).
12038: 
12039: Note that the backtrace is not perfect: We don't know which return stack
12040: entries are return addresses (so we may get false positives); and in
12041: some cases (e.g., for @code{abort"}) we cannot determine from the return
12042: address the word that pushed the return address, so for some return
12043: addresses you see no names in the return stack dump.
12044: 
12045: @cindex @code{catch} and backtraces
12046: The return stack dump represents the return stack at the time when a
12047: specific @code{throw} was executed.  In programs that make use of
12048: @code{catch}, it is not necessarily clear which @code{throw} should be
12049: used for the return stack dump (e.g., consider one @code{throw} that
12050: indicates an error, which is caught, and during recovery another error
12051: happens; which @code{throw} should be used for the stack dump?).  Gforth
12052: presents the return stack dump for the first @code{throw} after the last
12053: executed (not returned-to) @code{catch}; this works well in the usual
12054: case.
12055: 
12056: @cindex @code{gforth-fast} and backtraces
12057: @cindex @code{gforth-fast}, difference from @code{gforth}
12058: @cindex backtraces with @code{gforth-fast}
12059: @cindex return stack dump with @code{gforth-fast}
12060: @code{Gforth} is able to do a return stack dump for throws generated
12061: from primitives (e.g., invalid memory address, stack empty etc.);
12062: @code{gforth-fast} is only able to do a return stack dump from a
12063: directly called @code{throw} (including @code{abort} etc.).  Given an
12064: exception caused by a primitive in @code{gforth-fast}, you will
12065: typically see no return stack dump at all; however, if the exception is
12066: caught by @code{catch} (e.g., for restoring some state), and then
12067: @code{throw}n again, the return stack dump will be for the first such
12068: @code{throw}.
12069: 
12070: @c ******************************************************************
12071: @node Tools, ANS conformance, Error messages, Top
12072: @chapter Tools
12073: 
12074: @menu
12075: * ANS Report::                  Report the words used, sorted by wordset.
12076: @end menu
12077: 
12078: See also @ref{Emacs and Gforth}.
12079: 
12080: @node ANS Report,  , Tools, Tools
12081: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12082: @cindex @file{ans-report.fs}
12083: @cindex report the words used in your program
12084: @cindex words used in your program
12085: 
12086: If you want to label a Forth program as ANS Forth Program, you must
12087: document which wordsets the program uses; for extension wordsets, it is
12088: helpful to list the words the program requires from these wordsets
12089: (because Forth systems are allowed to provide only some words of them).
12090: 
12091: The @file{ans-report.fs} tool makes it easy for you to determine which
12092: words from which wordset and which non-ANS words your application
12093: uses. You simply have to include @file{ans-report.fs} before loading the
12094: program you want to check. After loading your program, you can get the
12095: report with @code{print-ans-report}. A typical use is to run this as
12096: batch job like this:
12097: @example
12098: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12099: @end example
12100: 
12101: The output looks like this (for @file{compat/control.fs}):
12102: @example
12103: The program uses the following words
12104: from CORE :
12105: : POSTPONE THEN ; immediate ?dup IF 0= 
12106: from BLOCK-EXT :
12107: \ 
12108: from FILE :
12109: ( 
12110: @end example
12111: 
12112: @subsection Caveats
12113: 
12114: Note that @file{ans-report.fs} just checks which words are used, not whether
12115: they are used in an ANS Forth conforming way!
12116: 
12117: Some words are defined in several wordsets in the
12118: standard. @file{ans-report.fs} reports them for only one of the
12119: wordsets, and not necessarily the one you expect. It depends on usage
12120: which wordset is the right one to specify. E.g., if you only use the
12121: compilation semantics of @code{S"}, it is a Core word; if you also use
12122: its interpretation semantics, it is a File word.
12123: 
12124: @c ******************************************************************
12125: @node ANS conformance, Standard vs Extensions, Tools, Top
12126: @chapter ANS conformance
12127: @cindex ANS conformance of Gforth
12128: 
12129: To the best of our knowledge, Gforth is an
12130: 
12131: ANS Forth System
12132: @itemize @bullet
12133: @item providing the Core Extensions word set
12134: @item providing the Block word set
12135: @item providing the Block Extensions word set
12136: @item providing the Double-Number word set
12137: @item providing the Double-Number Extensions word set
12138: @item providing the Exception word set
12139: @item providing the Exception Extensions word set
12140: @item providing the Facility word set
12141: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
12142: @item providing the File Access word set
12143: @item providing the File Access Extensions word set
12144: @item providing the Floating-Point word set
12145: @item providing the Floating-Point Extensions word set
12146: @item providing the Locals word set
12147: @item providing the Locals Extensions word set
12148: @item providing the Memory-Allocation word set
12149: @item providing the Memory-Allocation Extensions word set (that one's easy)
12150: @item providing the Programming-Tools word set
12151: @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
12152: @item providing the Search-Order word set
12153: @item providing the Search-Order Extensions word set
12154: @item providing the String word set
12155: @item providing the String Extensions word set (another easy one)
12156: @end itemize
12157: 
12158: Gforth has the following environmental restrictions:
12159: 
12160: @cindex environmental restrictions
12161: @itemize @bullet
12162: @item
12163: While processing the OS command line, if an exception is not caught,
12164: Gforth exits with a non-zero exit code instyead of performing QUIT.
12165: 
12166: @item
12167: When an @code{throw} is performed after a @code{query}, Gforth does not
12168: allways restore the input source specification in effect at the
12169: corresponding catch.
12170: 
12171: @end itemize
12172: 
12173: 
12174: @cindex system documentation
12175: In addition, ANS Forth systems are required to document certain
12176: implementation choices. This chapter tries to meet these
12177: requirements. In many cases it gives a way to ask the system for the
12178: information instead of providing the information directly, in
12179: particular, if the information depends on the processor, the operating
12180: system or the installation options chosen, or if they are likely to
12181: change during the maintenance of Gforth.
12182: 
12183: @comment The framework for the rest has been taken from pfe.
12184: 
12185: @menu
12186: * The Core Words::              
12187: * The optional Block word set::  
12188: * The optional Double Number word set::  
12189: * The optional Exception word set::  
12190: * The optional Facility word set::  
12191: * The optional File-Access word set::  
12192: * The optional Floating-Point word set::  
12193: * The optional Locals word set::  
12194: * The optional Memory-Allocation word set::  
12195: * The optional Programming-Tools word set::  
12196: * The optional Search-Order word set::  
12197: @end menu
12198: 
12199: 
12200: @c =====================================================================
12201: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12202: @comment  node-name,  next,  previous,  up
12203: @section The Core Words
12204: @c =====================================================================
12205: @cindex core words, system documentation
12206: @cindex system documentation, core words
12207: 
12208: @menu
12209: * core-idef::                   Implementation Defined Options                   
12210: * core-ambcond::                Ambiguous Conditions                
12211: * core-other::                  Other System Documentation                  
12212: @end menu
12213: 
12214: @c ---------------------------------------------------------------------
12215: @node core-idef, core-ambcond, The Core Words, The Core Words
12216: @subsection Implementation Defined Options
12217: @c ---------------------------------------------------------------------
12218: @cindex core words, implementation-defined options
12219: @cindex implementation-defined options, core words
12220: 
12221: 
12222: @table @i
12223: @item (Cell) aligned addresses:
12224: @cindex cell-aligned addresses
12225: @cindex aligned addresses
12226: processor-dependent. Gforth's alignment words perform natural alignment
12227: (e.g., an address aligned for a datum of size 8 is divisible by
12228: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12229: 
12230: @item @code{EMIT} and non-graphic characters:
12231: @cindex @code{EMIT} and non-graphic characters
12232: @cindex non-graphic characters and @code{EMIT}
12233: The character is output using the C library function (actually, macro)
12234: @code{putc}.
12235: 
12236: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12237: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12238: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12239: @cindex @code{ACCEPT}, editing
12240: @cindex @code{EXPECT}, editing
12241: This is modeled on the GNU readline library (@pxref{Readline
12242: Interaction, , Command Line Editing, readline, The GNU Readline
12243: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12244: producing a full word completion every time you type it (instead of
12245: producing the common prefix of all completions). @xref{Command-line editing}.
12246: 
12247: @item character set:
12248: @cindex character set
12249: The character set of your computer and display device. Gforth is
12250: 8-bit-clean (but some other component in your system may make trouble).
12251: 
12252: @item Character-aligned address requirements:
12253: @cindex character-aligned address requirements
12254: installation-dependent. Currently a character is represented by a C
12255: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12256: (Comments on that requested).
12257: 
12258: @item character-set extensions and matching of names:
12259: @cindex character-set extensions and matching of names
12260: @cindex case-sensitivity for name lookup
12261: @cindex name lookup, case-sensitivity
12262: @cindex locale and case-sensitivity
12263: Any character except the ASCII NUL character can be used in a
12264: name. Matching is case-insensitive (except in @code{TABLE}s). The
12265: matching is performed using the C library function @code{strncasecmp}, whose
12266: function is probably influenced by the locale. E.g., the @code{C} locale
12267: does not know about accents and umlauts, so they are matched
12268: case-sensitively in that locale. For portability reasons it is best to
12269: write programs such that they work in the @code{C} locale. Then one can
12270: use libraries written by a Polish programmer (who might use words
12271: containing ISO Latin-2 encoded characters) and by a French programmer
12272: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12273: funny results for some of the words (which ones, depends on the font you
12274: are using)). Also, the locale you prefer may not be available in other
12275: operating systems. Hopefully, Unicode will solve these problems one day.
12276: 
12277: @item conditions under which control characters match a space delimiter:
12278: @cindex space delimiters
12279: @cindex control characters as delimiters
12280: If @code{word} is called with the space character as a delimiter, all
12281: white-space characters (as identified by the C macro @code{isspace()})
12282: are delimiters. @code{Parse}, on the other hand, treats space like other
12283: delimiters.  @code{Parse-word}, which is used by the outer
12284: interpreter (aka text interpreter) by default, treats all white-space
12285: characters as delimiters.
12286: 
12287: @item format of the control-flow stack:
12288: @cindex control-flow stack, format
12289: The data stack is used as control-flow stack. The size of a control-flow
12290: stack item in cells is given by the constant @code{cs-item-size}. At the
12291: time of this writing, an item consists of a (pointer to a) locals list
12292: (third), an address in the code (second), and a tag for identifying the
12293: item (TOS). The following tags are used: @code{defstart},
12294: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12295: @code{scopestart}.
12296: 
12297: @item conversion of digits > 35
12298: @cindex digits > 35
12299: The characters @code{[\]^_'} are the digits with the decimal value
12300: 36@minus{}41. There is no way to input many of the larger digits.
12301: 
12302: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12303: @cindex @code{EXPECT}, display after end of input
12304: @cindex @code{ACCEPT}, display after end of input
12305: The cursor is moved to the end of the entered string. If the input is
12306: terminated using the @kbd{Return} key, a space is typed.
12307: 
12308: @item exception abort sequence of @code{ABORT"}:
12309: @cindex exception abort sequence of @code{ABORT"}
12310: @cindex @code{ABORT"}, exception abort sequence
12311: The error string is stored into the variable @code{"error} and a
12312: @code{-2 throw} is performed.
12313: 
12314: @item input line terminator:
12315: @cindex input line terminator
12316: @cindex line terminator on input
12317: @cindex newline character on input
12318: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12319: lines. One of these characters is typically produced when you type the
12320: @kbd{Enter} or @kbd{Return} key.
12321: 
12322: @item maximum size of a counted string:
12323: @cindex maximum size of a counted string
12324: @cindex counted string, maximum size
12325: @code{s" /counted-string" environment? drop .}. Currently 255 characters
12326: on all platforms, but this may change.
12327: 
12328: @item maximum size of a parsed string:
12329: @cindex maximum size of a parsed string
12330: @cindex parsed string, maximum size
12331: Given by the constant @code{/line}. Currently 255 characters.
12332: 
12333: @item maximum size of a definition name, in characters:
12334: @cindex maximum size of a definition name, in characters
12335: @cindex name, maximum length
12336: MAXU/8
12337: 
12338: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12339: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12340: @cindex @code{ENVIRONMENT?} string length, maximum
12341: MAXU/8
12342: 
12343: @item method of selecting the user input device:
12344: @cindex user input device, method of selecting
12345: The user input device is the standard input. There is currently no way to
12346: change it from within Gforth. However, the input can typically be
12347: redirected in the command line that starts Gforth.
12348: 
12349: @item method of selecting the user output device:
12350: @cindex user output device, method of selecting
12351: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
12352: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12353: output when the user output device is a terminal, otherwise the output
12354: is buffered.
12355: 
12356: @item methods of dictionary compilation:
12357: What are we expected to document here?
12358: 
12359: @item number of bits in one address unit:
12360: @cindex number of bits in one address unit
12361: @cindex address unit, size in bits
12362: @code{s" address-units-bits" environment? drop .}. 8 in all current
12363: platforms.
12364: 
12365: @item number representation and arithmetic:
12366: @cindex number representation and arithmetic
12367: Processor-dependent. Binary two's complement on all current platforms.
12368: 
12369: @item ranges for integer types:
12370: @cindex ranges for integer types
12371: @cindex integer types, ranges
12372: Installation-dependent. Make environmental queries for @code{MAX-N},
12373: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12374: unsigned (and positive) types is 0. The lower bound for signed types on
12375: two's complement and one's complement machines machines can be computed
12376: by adding 1 to the upper bound.
12377: 
12378: @item read-only data space regions:
12379: @cindex read-only data space regions
12380: @cindex data-space, read-only regions
12381: The whole Forth data space is writable.
12382: 
12383: @item size of buffer at @code{WORD}:
12384: @cindex size of buffer at @code{WORD}
12385: @cindex @code{WORD} buffer size
12386: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12387: shared with the pictured numeric output string. If overwriting
12388: @code{PAD} is acceptable, it is as large as the remaining dictionary
12389: space, although only as much can be sensibly used as fits in a counted
12390: string.
12391: 
12392: @item size of one cell in address units:
12393: @cindex cell size
12394: @code{1 cells .}.
12395: 
12396: @item size of one character in address units:
12397: @cindex char size
12398: @code{1 chars .}. 1 on all current platforms.
12399: 
12400: @item size of the keyboard terminal buffer:
12401: @cindex size of the keyboard terminal buffer
12402: @cindex terminal buffer, size
12403: Varies. You can determine the size at a specific time using @code{lp@@
12404: tib - .}. It is shared with the locals stack and TIBs of files that
12405: include the current file. You can change the amount of space for TIBs
12406: and locals stack at Gforth startup with the command line option
12407: @code{-l}.
12408: 
12409: @item size of the pictured numeric output buffer:
12410: @cindex size of the pictured numeric output buffer
12411: @cindex pictured numeric output buffer, size
12412: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12413: shared with @code{WORD}.
12414: 
12415: @item size of the scratch area returned by @code{PAD}:
12416: @cindex size of the scratch area returned by @code{PAD}
12417: @cindex @code{PAD} size
12418: The remainder of dictionary space. @code{unused pad here - - .}.
12419: 
12420: @item system case-sensitivity characteristics:
12421: @cindex case-sensitivity characteristics
12422: Dictionary searches are case-insensitive (except in
12423: @code{TABLE}s). However, as explained above under @i{character-set
12424: extensions}, the matching for non-ASCII characters is determined by the
12425: locale you are using. In the default @code{C} locale all non-ASCII
12426: characters are matched case-sensitively.
12427: 
12428: @item system prompt:
12429: @cindex system prompt
12430: @cindex prompt
12431: @code{ ok} in interpret state, @code{ compiled} in compile state.
12432: 
12433: @item division rounding:
12434: @cindex division rounding
12435: installation dependent. @code{s" floored" environment? drop .}. We leave
12436: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12437: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12438: 
12439: @item values of @code{STATE} when true:
12440: @cindex @code{STATE} values
12441: -1.
12442: 
12443: @item values returned after arithmetic overflow:
12444: On two's complement machines, arithmetic is performed modulo
12445: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12446: arithmetic (with appropriate mapping for signed types). Division by zero
12447: typically results in a @code{-55 throw} (Floating-point unidentified
12448: fault) or @code{-10 throw} (divide by zero).
12449: 
12450: @item whether the current definition can be found after @t{DOES>}:
12451: @cindex @t{DOES>}, visibility of current definition
12452: No.
12453: 
12454: @end table
12455: 
12456: @c ---------------------------------------------------------------------
12457: @node core-ambcond, core-other, core-idef, The Core Words
12458: @subsection Ambiguous conditions
12459: @c ---------------------------------------------------------------------
12460: @cindex core words, ambiguous conditions
12461: @cindex ambiguous conditions, core words
12462: 
12463: @table @i
12464: 
12465: @item a name is neither a word nor a number:
12466: @cindex name not found
12467: @cindex undefined word
12468: @code{-13 throw} (Undefined word).
12469: 
12470: @item a definition name exceeds the maximum length allowed:
12471: @cindex word name too long
12472: @code{-19 throw} (Word name too long)
12473: 
12474: @item addressing a region not inside the various data spaces of the forth system:
12475: @cindex Invalid memory address
12476: The stacks, code space and header space are accessible. Machine code space is
12477: typically readable. Accessing other addresses gives results dependent on
12478: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12479: address).
12480: 
12481: @item argument type incompatible with parameter:
12482: @cindex argument type mismatch
12483: This is usually not caught. Some words perform checks, e.g., the control
12484: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12485: mismatch).
12486: 
12487: @item attempting to obtain the execution token of a word with undefined execution semantics:
12488: @cindex Interpreting a compile-only word, for @code{'} etc.
12489: @cindex execution token of words with undefined execution semantics
12490: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12491: get an execution token for @code{compile-only-error} (which performs a
12492: @code{-14 throw} when executed).
12493: 
12494: @item dividing by zero:
12495: @cindex dividing by zero
12496: @cindex floating point unidentified fault, integer division
12497: On some platforms, this produces a @code{-10 throw} (Division by
12498: zero); on other systems, this typically results in a @code{-55 throw}
12499: (Floating-point unidentified fault).
12500: 
12501: @item insufficient data stack or return stack space:
12502: @cindex insufficient data stack or return stack space
12503: @cindex stack overflow
12504: @cindex address alignment exception, stack overflow
12505: @cindex Invalid memory address, stack overflow
12506: Depending on the operating system, the installation, and the invocation
12507: of Gforth, this is either checked by the memory management hardware, or
12508: it is not checked. If it is checked, you typically get a @code{-3 throw}
12509: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12510: throw} (Invalid memory address) (depending on the platform and how you
12511: achieved the overflow) as soon as the overflow happens. If it is not
12512: checked, overflows typically result in mysterious illegal memory
12513: accesses, producing @code{-9 throw} (Invalid memory address) or
12514: @code{-23 throw} (Address alignment exception); they might also destroy
12515: the internal data structure of @code{ALLOCATE} and friends, resulting in
12516: various errors in these words.
12517: 
12518: @item insufficient space for loop control parameters:
12519: @cindex insufficient space for loop control parameters
12520: Like other return stack overflows.
12521: 
12522: @item insufficient space in the dictionary:
12523: @cindex insufficient space in the dictionary
12524: @cindex dictionary overflow
12525: If you try to allot (either directly with @code{allot}, or indirectly
12526: with @code{,}, @code{create} etc.) more memory than available in the
12527: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12528: to access memory beyond the end of the dictionary, the results are
12529: similar to stack overflows.
12530: 
12531: @item interpreting a word with undefined interpretation semantics:
12532: @cindex interpreting a word with undefined interpretation semantics
12533: @cindex Interpreting a compile-only word
12534: For some words, we have defined interpretation semantics. For the
12535: others: @code{-14 throw} (Interpreting a compile-only word).
12536: 
12537: @item modifying the contents of the input buffer or a string literal:
12538: @cindex modifying the contents of the input buffer or a string literal
12539: These are located in writable memory and can be modified.
12540: 
12541: @item overflow of the pictured numeric output string:
12542: @cindex overflow of the pictured numeric output string
12543: @cindex pictured numeric output string, overflow
12544: @code{-17 throw} (Pictured numeric ouput string overflow).
12545: 
12546: @item parsed string overflow:
12547: @cindex parsed string overflow
12548: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12549: 
12550: @item producing a result out of range:
12551: @cindex result out of range
12552: On two's complement machines, arithmetic is performed modulo
12553: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12554: arithmetic (with appropriate mapping for signed types). Division by zero
12555: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12556: throw} (floating point unidentified fault). @code{convert} and
12557: @code{>number} currently overflow silently.
12558: 
12559: @item reading from an empty data or return stack:
12560: @cindex stack empty
12561: @cindex stack underflow
12562: @cindex return stack underflow
12563: The data stack is checked by the outer (aka text) interpreter after
12564: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12565: underflow) is performed. Apart from that, stacks may be checked or not,
12566: depending on operating system, installation, and invocation. If they are
12567: caught by a check, they typically result in @code{-4 throw} (Stack
12568: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12569: (Invalid memory address), depending on the platform and which stack
12570: underflows and by how much. Note that even if the system uses checking
12571: (through the MMU), your program may have to underflow by a significant
12572: number of stack items to trigger the reaction (the reason for this is
12573: that the MMU, and therefore the checking, works with a page-size
12574: granularity).  If there is no checking, the symptoms resulting from an
12575: underflow are similar to those from an overflow.  Unbalanced return
12576: stack errors can result in a variety of symptoms, including @code{-9 throw}
12577: (Invalid memory address) and Illegal Instruction (typically @code{-260
12578: throw}).
12579: 
12580: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12581: @cindex unexpected end of the input buffer
12582: @cindex zero-length string as a name
12583: @cindex Attempt to use zero-length string as a name
12584: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12585: use zero-length string as a name). Words like @code{'} probably will not
12586: find what they search. Note that it is possible to create zero-length
12587: names with @code{nextname} (should it not?).
12588: 
12589: @item @code{>IN} greater than input buffer:
12590: @cindex @code{>IN} greater than input buffer
12591: The next invocation of a parsing word returns a string with length 0.
12592: 
12593: @item @code{RECURSE} appears after @code{DOES>}:
12594: @cindex @code{RECURSE} appears after @code{DOES>}
12595: Compiles a recursive call to the defining word, not to the defined word.
12596: 
12597: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12598: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
12599: @cindex argument type mismatch, @code{RESTORE-INPUT}
12600: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12601: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12602: the end of the file was reached), its source-id may be
12603: reused. Therefore, restoring an input source specification referencing a
12604: closed file may lead to unpredictable results instead of a @code{-12
12605: THROW}.
12606: 
12607: In the future, Gforth may be able to restore input source specifications
12608: from other than the current input source.
12609: 
12610: @item data space containing definitions gets de-allocated:
12611: @cindex data space containing definitions gets de-allocated
12612: Deallocation with @code{allot} is not checked. This typically results in
12613: memory access faults or execution of illegal instructions.
12614: 
12615: @item data space read/write with incorrect alignment:
12616: @cindex data space read/write with incorrect alignment
12617: @cindex alignment faults
12618: @cindex address alignment exception
12619: Processor-dependent. Typically results in a @code{-23 throw} (Address
12620: alignment exception). Under Linux-Intel on a 486 or later processor with
12621: alignment turned on, incorrect alignment results in a @code{-9 throw}
12622: (Invalid memory address). There are reportedly some processors with
12623: alignment restrictions that do not report violations.
12624: 
12625: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12626: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12627: Like other alignment errors.
12628: 
12629: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12630: Like other stack underflows.
12631: 
12632: @item loop control parameters not available:
12633: @cindex loop control parameters not available
12634: Not checked. The counted loop words simply assume that the top of return
12635: stack items are loop control parameters and behave accordingly.
12636: 
12637: @item most recent definition does not have a name (@code{IMMEDIATE}):
12638: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12639: @cindex last word was headerless
12640: @code{abort" last word was headerless"}.
12641: 
12642: @item name not defined by @code{VALUE} used by @code{TO}:
12643: @cindex name not defined by @code{VALUE} used by @code{TO}
12644: @cindex @code{TO} on non-@code{VALUE}s
12645: @cindex Invalid name argument, @code{TO}
12646: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12647: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12648: 
12649: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12650: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
12651: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
12652: @code{-13 throw} (Undefined word)
12653: 
12654: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12655: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12656: Gforth behaves as if they were of the same type. I.e., you can predict
12657: the behaviour by interpreting all parameters as, e.g., signed.
12658: 
12659: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12660: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12661: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12662: compilation semantics of @code{TO}.
12663: 
12664: @item String longer than a counted string returned by @code{WORD}:
12665: @cindex string longer than a counted string returned by @code{WORD}
12666: @cindex @code{WORD}, string overflow
12667: Not checked. The string will be ok, but the count will, of course,
12668: contain only the least significant bits of the length.
12669: 
12670: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12671: @cindex @code{LSHIFT}, large shift counts
12672: @cindex @code{RSHIFT}, large shift counts
12673: Processor-dependent. Typical behaviours are returning 0 and using only
12674: the low bits of the shift count.
12675: 
12676: @item word not defined via @code{CREATE}:
12677: @cindex @code{>BODY} of non-@code{CREATE}d words
12678: @code{>BODY} produces the PFA of the word no matter how it was defined.
12679: 
12680: @cindex @code{DOES>} of non-@code{CREATE}d words
12681: @code{DOES>} changes the execution semantics of the last defined word no
12682: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12683: @code{CREATE , DOES>}.
12684: 
12685: @item words improperly used outside @code{<#} and @code{#>}:
12686: Not checked. As usual, you can expect memory faults.
12687: 
12688: @end table
12689: 
12690: 
12691: @c ---------------------------------------------------------------------
12692: @node core-other,  , core-ambcond, The Core Words
12693: @subsection Other system documentation
12694: @c ---------------------------------------------------------------------
12695: @cindex other system documentation, core words
12696: @cindex core words, other system documentation
12697: 
12698: @table @i
12699: @item nonstandard words using @code{PAD}:
12700: @cindex @code{PAD} use by nonstandard words
12701: None.
12702: 
12703: @item operator's terminal facilities available:
12704: @cindex operator's terminal facilities available
12705: After processing the OS's command line, Gforth goes into interactive mode,
12706: and you can give commands to Gforth interactively. The actual facilities
12707: available depend on how you invoke Gforth.
12708: 
12709: @item program data space available:
12710: @cindex program data space available
12711: @cindex data space available
12712: @code{UNUSED .} gives the remaining dictionary space. The total
12713: dictionary space can be specified with the @code{-m} switch
12714: (@pxref{Invoking Gforth}) when Gforth starts up.
12715: 
12716: @item return stack space available:
12717: @cindex return stack space available
12718: You can compute the total return stack space in cells with
12719: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12720: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12721: 
12722: @item stack space available:
12723: @cindex stack space available
12724: You can compute the total data stack space in cells with
12725: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12726: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12727: 
12728: @item system dictionary space required, in address units:
12729: @cindex system dictionary space required, in address units
12730: Type @code{here forthstart - .} after startup. At the time of this
12731: writing, this gives 80080 (bytes) on a 32-bit system.
12732: @end table
12733: 
12734: 
12735: @c =====================================================================
12736: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12737: @section The optional Block word set
12738: @c =====================================================================
12739: @cindex system documentation, block words
12740: @cindex block words, system documentation
12741: 
12742: @menu
12743: * block-idef::                  Implementation Defined Options
12744: * block-ambcond::               Ambiguous Conditions               
12745: * block-other::                 Other System Documentation                 
12746: @end menu
12747: 
12748: 
12749: @c ---------------------------------------------------------------------
12750: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12751: @subsection Implementation Defined Options
12752: @c ---------------------------------------------------------------------
12753: @cindex implementation-defined options, block words
12754: @cindex block words, implementation-defined options
12755: 
12756: @table @i
12757: @item the format for display by @code{LIST}:
12758: @cindex @code{LIST} display format
12759: First the screen number is displayed, then 16 lines of 64 characters,
12760: each line preceded by the line number.
12761: 
12762: @item the length of a line affected by @code{\}:
12763: @cindex length of a line affected by @code{\}
12764: @cindex @code{\}, line length in blocks
12765: 64 characters.
12766: @end table
12767: 
12768: 
12769: @c ---------------------------------------------------------------------
12770: @node block-ambcond, block-other, block-idef, The optional Block word set
12771: @subsection Ambiguous conditions
12772: @c ---------------------------------------------------------------------
12773: @cindex block words, ambiguous conditions
12774: @cindex ambiguous conditions, block words
12775: 
12776: @table @i
12777: @item correct block read was not possible:
12778: @cindex block read not possible
12779: Typically results in a @code{throw} of some OS-derived value (between
12780: -512 and -2048). If the blocks file was just not long enough, blanks are
12781: supplied for the missing portion.
12782: 
12783: @item I/O exception in block transfer:
12784: @cindex I/O exception in block transfer
12785: @cindex block transfer, I/O exception
12786: Typically results in a @code{throw} of some OS-derived value (between
12787: -512 and -2048).
12788: 
12789: @item invalid block number:
12790: @cindex invalid block number
12791: @cindex block number invalid
12792: @code{-35 throw} (Invalid block number)
12793: 
12794: @item a program directly alters the contents of @code{BLK}:
12795: @cindex @code{BLK}, altering @code{BLK}
12796: The input stream is switched to that other block, at the same
12797: position. If the storing to @code{BLK} happens when interpreting
12798: non-block input, the system will get quite confused when the block ends.
12799: 
12800: @item no current block buffer for @code{UPDATE}:
12801: @cindex @code{UPDATE}, no current block buffer
12802: @code{UPDATE} has no effect.
12803: 
12804: @end table
12805: 
12806: @c ---------------------------------------------------------------------
12807: @node block-other,  , block-ambcond, The optional Block word set
12808: @subsection Other system documentation
12809: @c ---------------------------------------------------------------------
12810: @cindex other system documentation, block words
12811: @cindex block words, other system documentation
12812: 
12813: @table @i
12814: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12815: No restrictions (yet).
12816: 
12817: @item the number of blocks available for source and data:
12818: depends on your disk space.
12819: 
12820: @end table
12821: 
12822: 
12823: @c =====================================================================
12824: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12825: @section The optional Double Number word set
12826: @c =====================================================================
12827: @cindex system documentation, double words
12828: @cindex double words, system documentation
12829: 
12830: @menu
12831: * double-ambcond::              Ambiguous Conditions              
12832: @end menu
12833: 
12834: 
12835: @c ---------------------------------------------------------------------
12836: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
12837: @subsection Ambiguous conditions
12838: @c ---------------------------------------------------------------------
12839: @cindex double words, ambiguous conditions
12840: @cindex ambiguous conditions, double words
12841: 
12842: @table @i
12843: @item @i{d} outside of range of @i{n} in @code{D>S}:
12844: @cindex @code{D>S}, @i{d} out of range of @i{n} 
12845: The least significant cell of @i{d} is produced.
12846: 
12847: @end table
12848: 
12849: 
12850: @c =====================================================================
12851: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12852: @section The optional Exception word set
12853: @c =====================================================================
12854: @cindex system documentation, exception words
12855: @cindex exception words, system documentation
12856: 
12857: @menu
12858: * exception-idef::              Implementation Defined Options              
12859: @end menu
12860: 
12861: 
12862: @c ---------------------------------------------------------------------
12863: @node exception-idef,  , The optional Exception word set, The optional Exception word set
12864: @subsection Implementation Defined Options
12865: @c ---------------------------------------------------------------------
12866: @cindex implementation-defined options, exception words
12867: @cindex exception words, implementation-defined options
12868: 
12869: @table @i
12870: @item @code{THROW}-codes used in the system:
12871: @cindex @code{THROW}-codes used in the system
12872: The codes -256@minus{}-511 are used for reporting signals. The mapping
12873: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
12874: codes -512@minus{}-2047 are used for OS errors (for file and memory
12875: allocation operations). The mapping from OS error numbers to throw codes
12876: is -512@minus{}@code{errno}. One side effect of this mapping is that
12877: undefined OS errors produce a message with a strange number; e.g.,
12878: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12879: @end table
12880: 
12881: @c =====================================================================
12882: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12883: @section The optional Facility word set
12884: @c =====================================================================
12885: @cindex system documentation, facility words
12886: @cindex facility words, system documentation
12887: 
12888: @menu
12889: * facility-idef::               Implementation Defined Options               
12890: * facility-ambcond::            Ambiguous Conditions            
12891: @end menu
12892: 
12893: 
12894: @c ---------------------------------------------------------------------
12895: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12896: @subsection Implementation Defined Options
12897: @c ---------------------------------------------------------------------
12898: @cindex implementation-defined options, facility words
12899: @cindex facility words, implementation-defined options
12900: 
12901: @table @i
12902: @item encoding of keyboard events (@code{EKEY}):
12903: @cindex keyboard events, encoding in @code{EKEY}
12904: @cindex @code{EKEY}, encoding of keyboard events
12905: Keys corresponding to ASCII characters are encoded as ASCII characters.
12906: Other keys are encoded with the constants @code{k-left}, @code{k-right},
12907: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
12908: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
12909: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
12910: 
12911: 
12912: @item duration of a system clock tick:
12913: @cindex duration of a system clock tick
12914: @cindex clock tick duration
12915: System dependent. With respect to @code{MS}, the time is specified in
12916: microseconds. How well the OS and the hardware implement this, is
12917: another question.
12918: 
12919: @item repeatability to be expected from the execution of @code{MS}:
12920: @cindex repeatability to be expected from the execution of @code{MS}
12921: @cindex @code{MS}, repeatability to be expected
12922: System dependent. On Unix, a lot depends on load. If the system is
12923: lightly loaded, and the delay is short enough that Gforth does not get
12924: swapped out, the performance should be acceptable. Under MS-DOS and
12925: other single-tasking systems, it should be good.
12926: 
12927: @end table
12928: 
12929: 
12930: @c ---------------------------------------------------------------------
12931: @node facility-ambcond,  , facility-idef, The optional Facility word set
12932: @subsection Ambiguous conditions
12933: @c ---------------------------------------------------------------------
12934: @cindex facility words, ambiguous conditions
12935: @cindex ambiguous conditions, facility words
12936: 
12937: @table @i
12938: @item @code{AT-XY} can't be performed on user output device:
12939: @cindex @code{AT-XY} can't be performed on user output device
12940: Largely terminal dependent. No range checks are done on the arguments.
12941: No errors are reported. You may see some garbage appearing, you may see
12942: simply nothing happen.
12943: 
12944: @end table
12945: 
12946: 
12947: @c =====================================================================
12948: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
12949: @section The optional File-Access word set
12950: @c =====================================================================
12951: @cindex system documentation, file words
12952: @cindex file words, system documentation
12953: 
12954: @menu
12955: * file-idef::                   Implementation Defined Options
12956: * file-ambcond::                Ambiguous Conditions                
12957: @end menu
12958: 
12959: @c ---------------------------------------------------------------------
12960: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
12961: @subsection Implementation Defined Options
12962: @c ---------------------------------------------------------------------
12963: @cindex implementation-defined options, file words
12964: @cindex file words, implementation-defined options
12965: 
12966: @table @i
12967: @item file access methods used:
12968: @cindex file access methods used
12969: @code{R/O}, @code{R/W} and @code{BIN} work as you would
12970: expect. @code{W/O} translates into the C file opening mode @code{w} (or
12971: @code{wb}): The file is cleared, if it exists, and created, if it does
12972: not (with both @code{open-file} and @code{create-file}).  Under Unix
12973: @code{create-file} creates a file with 666 permissions modified by your
12974: umask.
12975: 
12976: @item file exceptions:
12977: @cindex file exceptions
12978: The file words do not raise exceptions (except, perhaps, memory access
12979: faults when you pass illegal addresses or file-ids).
12980: 
12981: @item file line terminator:
12982: @cindex file line terminator
12983: System-dependent. Gforth uses C's newline character as line
12984: terminator. What the actual character code(s) of this are is
12985: system-dependent.
12986: 
12987: @item file name format:
12988: @cindex file name format
12989: System dependent. Gforth just uses the file name format of your OS.
12990: 
12991: @item information returned by @code{FILE-STATUS}:
12992: @cindex @code{FILE-STATUS}, returned information
12993: @code{FILE-STATUS} returns the most powerful file access mode allowed
12994: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
12995: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
12996: along with the returned mode.
12997: 
12998: @item input file state after an exception when including source:
12999: @cindex exception when including source
13000: All files that are left via the exception are closed.
13001: 
13002: @item @i{ior} values and meaning:
13003: @cindex @i{ior} values and meaning
13004: @cindex @i{wior} values and meaning
13005: The @i{ior}s returned by the file and memory allocation words are
13006: intended as throw codes. They typically are in the range
13007: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13008: @i{ior}s is -512@minus{}@i{errno}.
13009: 
13010: @item maximum depth of file input nesting:
13011: @cindex maximum depth of file input nesting
13012: @cindex file input nesting, maximum depth
13013: limited by the amount of return stack, locals/TIB stack, and the number
13014: of open files available. This should not give you troubles.
13015: 
13016: @item maximum size of input line:
13017: @cindex maximum size of input line
13018: @cindex input line size, maximum
13019: @code{/line}. Currently 255.
13020: 
13021: @item methods of mapping block ranges to files:
13022: @cindex mapping block ranges to files
13023: @cindex files containing blocks
13024: @cindex blocks in files
13025: By default, blocks are accessed in the file @file{blocks.fb} in the
13026: current working directory. The file can be switched with @code{USE}.
13027: 
13028: @item number of string buffers provided by @code{S"}:
13029: @cindex @code{S"}, number of string buffers
13030: 1
13031: 
13032: @item size of string buffer used by @code{S"}:
13033: @cindex @code{S"}, size of string buffer
13034: @code{/line}. currently 255.
13035: 
13036: @end table
13037: 
13038: @c ---------------------------------------------------------------------
13039: @node file-ambcond,  , file-idef, The optional File-Access word set
13040: @subsection Ambiguous conditions
13041: @c ---------------------------------------------------------------------
13042: @cindex file words, ambiguous conditions
13043: @cindex ambiguous conditions, file words
13044: 
13045: @table @i
13046: @item attempting to position a file outside its boundaries:
13047: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13048: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13049: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13050: 
13051: @item attempting to read from file positions not yet written:
13052: @cindex reading from file positions not yet written
13053: End-of-file, i.e., zero characters are read and no error is reported.
13054: 
13055: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13056: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
13057: An appropriate exception may be thrown, but a memory fault or other
13058: problem is more probable.
13059: 
13060: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13061: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13062: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13063: The @i{ior} produced by the operation, that discovered the problem, is
13064: thrown.
13065: 
13066: @item named file cannot be opened (@code{INCLUDED}):
13067: @cindex @code{INCLUDED}, named file cannot be opened
13068: The @i{ior} produced by @code{open-file} is thrown.
13069: 
13070: @item requesting an unmapped block number:
13071: @cindex unmapped block numbers
13072: There are no unmapped legal block numbers. On some operating systems,
13073: writing a block with a large number may overflow the file system and
13074: have an error message as consequence.
13075: 
13076: @item using @code{source-id} when @code{blk} is non-zero:
13077: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13078: @code{source-id} performs its function. Typically it will give the id of
13079: the source which loaded the block. (Better ideas?)
13080: 
13081: @end table
13082: 
13083: 
13084: @c =====================================================================
13085: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13086: @section The optional Floating-Point word set
13087: @c =====================================================================
13088: @cindex system documentation, floating-point words
13089: @cindex floating-point words, system documentation
13090: 
13091: @menu
13092: * floating-idef::               Implementation Defined Options
13093: * floating-ambcond::            Ambiguous Conditions            
13094: @end menu
13095: 
13096: 
13097: @c ---------------------------------------------------------------------
13098: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13099: @subsection Implementation Defined Options
13100: @c ---------------------------------------------------------------------
13101: @cindex implementation-defined options, floating-point words
13102: @cindex floating-point words, implementation-defined options
13103: 
13104: @table @i
13105: @item format and range of floating point numbers:
13106: @cindex format and range of floating point numbers
13107: @cindex floating point numbers, format and range
13108: System-dependent; the @code{double} type of C.
13109: 
13110: @item results of @code{REPRESENT} when @i{float} is out of range:
13111: @cindex  @code{REPRESENT}, results when @i{float} is out of range
13112: System dependent; @code{REPRESENT} is implemented using the C library
13113: function @code{ecvt()} and inherits its behaviour in this respect.
13114: 
13115: @item rounding or truncation of floating-point numbers:
13116: @cindex rounding of floating-point numbers
13117: @cindex truncation of floating-point numbers
13118: @cindex floating-point numbers, rounding or truncation
13119: System dependent; the rounding behaviour is inherited from the hosting C
13120: compiler. IEEE-FP-based (i.e., most) systems by default round to
13121: nearest, and break ties by rounding to even (i.e., such that the last
13122: bit of the mantissa is 0).
13123: 
13124: @item size of floating-point stack:
13125: @cindex floating-point stack size
13126: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13127: the floating-point stack (in floats). You can specify this on startup
13128: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13129: 
13130: @item width of floating-point stack:
13131: @cindex floating-point stack width 
13132: @code{1 floats}.
13133: 
13134: @end table
13135: 
13136: 
13137: @c ---------------------------------------------------------------------
13138: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
13139: @subsection Ambiguous conditions
13140: @c ---------------------------------------------------------------------
13141: @cindex floating-point words, ambiguous conditions
13142: @cindex ambiguous conditions, floating-point words
13143: 
13144: @table @i
13145: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
13146: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
13147: System-dependent. Typically results in a @code{-23 THROW} like other
13148: alignment violations.
13149: 
13150: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
13151: @cindex @code{f@@} used with an address that is not float aligned
13152: @cindex @code{f!} used with an address that is not float aligned
13153: System-dependent. Typically results in a @code{-23 THROW} like other
13154: alignment violations.
13155: 
13156: @item floating-point result out of range:
13157: @cindex floating-point result out of range
13158: System-dependent. Can result in a @code{-43 throw} (floating point
13159: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13160: (floating point inexact result), @code{-55 THROW} (Floating-point
13161: unidentified fault), or can produce a special value representing, e.g.,
13162: Infinity.
13163: 
13164: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
13165: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
13166: System-dependent. Typically results in an alignment fault like other
13167: alignment violations.
13168: 
13169: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13170: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
13171: The floating-point number is converted into decimal nonetheless.
13172: 
13173: @item Both arguments are equal to zero (@code{FATAN2}):
13174: @cindex @code{FATAN2}, both arguments are equal to zero
13175: System-dependent. @code{FATAN2} is implemented using the C library
13176: function @code{atan2()}.
13177: 
13178: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13179: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13180: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
13181: because of small errors and the tan will be a very large (or very small)
13182: but finite number.
13183: 
13184: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13185: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
13186: The result is rounded to the nearest float.
13187: 
13188: @item dividing by zero:
13189: @cindex dividing by zero, floating-point
13190: @cindex floating-point dividing by zero
13191: @cindex floating-point unidentified fault, FP divide-by-zero
13192: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13193: (floating point divide by zero) or @code{-55 throw} (Floating-point
13194: unidentified fault).
13195: 
13196: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13197: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13198: System dependent. On IEEE-FP based systems the number is converted into
13199: an infinity.
13200: 
13201: @item @i{float}<1 (@code{FACOSH}):
13202: @cindex @code{FACOSH}, @i{float}<1
13203: @cindex floating-point unidentified fault, @code{FACOSH}
13204: Platform-dependent; on IEEE-FP systems typically produces a NaN.
13205: 
13206: @item @i{float}=<-1 (@code{FLNP1}):
13207: @cindex @code{FLNP1}, @i{float}=<-1
13208: @cindex floating-point unidentified fault, @code{FLNP1}
13209: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13210: negative infinity for @i{float}=-1).
13211: 
13212: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13213: @cindex @code{FLN}, @i{float}=<0
13214: @cindex @code{FLOG}, @i{float}=<0
13215: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
13216: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13217: negative infinity for @i{float}=0).
13218: 
13219: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13220: @cindex @code{FASINH}, @i{float}<0
13221: @cindex @code{FSQRT}, @i{float}<0
13222: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
13223: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13224: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13225: C library?).
13226: 
13227: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13228: @cindex @code{FACOS}, |@i{float}|>1
13229: @cindex @code{FASIN}, |@i{float}|>1
13230: @cindex @code{FATANH}, |@i{float}|>1
13231: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
13232: Platform-dependent; IEEE-FP systems typically produce a NaN.
13233: 
13234: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13235: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
13236: @cindex floating-point unidentified fault, @code{F>D}
13237: Platform-dependent; typically, some double number is produced and no
13238: error is reported.
13239: 
13240: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13241: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
13242: @code{Precision} characters of the numeric output area are used.  If
13243: @code{precision} is too high, these words will smash the data or code
13244: close to @code{here}.
13245: @end table
13246: 
13247: @c =====================================================================
13248: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13249: @section The optional Locals word set
13250: @c =====================================================================
13251: @cindex system documentation, locals words
13252: @cindex locals words, system documentation
13253: 
13254: @menu
13255: * locals-idef::                 Implementation Defined Options                 
13256: * locals-ambcond::              Ambiguous Conditions              
13257: @end menu
13258: 
13259: 
13260: @c ---------------------------------------------------------------------
13261: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13262: @subsection Implementation Defined Options
13263: @c ---------------------------------------------------------------------
13264: @cindex implementation-defined options, locals words
13265: @cindex locals words, implementation-defined options
13266: 
13267: @table @i
13268: @item maximum number of locals in a definition:
13269: @cindex maximum number of locals in a definition
13270: @cindex locals, maximum number in a definition
13271: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13272: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13273: characters. The number of locals in a definition is bounded by the size
13274: of locals-buffer, which contains the names of the locals.
13275: 
13276: @end table
13277: 
13278: 
13279: @c ---------------------------------------------------------------------
13280: @node locals-ambcond,  , locals-idef, The optional Locals word set
13281: @subsection Ambiguous conditions
13282: @c ---------------------------------------------------------------------
13283: @cindex locals words, ambiguous conditions
13284: @cindex ambiguous conditions, locals words
13285: 
13286: @table @i
13287: @item executing a named local in interpretation state:
13288: @cindex local in interpretation state
13289: @cindex Interpreting a compile-only word, for a local
13290: Locals have no interpretation semantics. If you try to perform the
13291: interpretation semantics, you will get a @code{-14 throw} somewhere
13292: (Interpreting a compile-only word). If you perform the compilation
13293: semantics, the locals access will be compiled (irrespective of state).
13294: 
13295: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
13296: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13297: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13298: @cindex Invalid name argument, @code{TO}
13299: @code{-32 throw} (Invalid name argument)
13300: 
13301: @end table
13302: 
13303: 
13304: @c =====================================================================
13305: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13306: @section The optional Memory-Allocation word set
13307: @c =====================================================================
13308: @cindex system documentation, memory-allocation words
13309: @cindex memory-allocation words, system documentation
13310: 
13311: @menu
13312: * memory-idef::                 Implementation Defined Options                 
13313: @end menu
13314: 
13315: 
13316: @c ---------------------------------------------------------------------
13317: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13318: @subsection Implementation Defined Options
13319: @c ---------------------------------------------------------------------
13320: @cindex implementation-defined options, memory-allocation words
13321: @cindex memory-allocation words, implementation-defined options
13322: 
13323: @table @i
13324: @item values and meaning of @i{ior}:
13325: @cindex  @i{ior} values and meaning
13326: The @i{ior}s returned by the file and memory allocation words are
13327: intended as throw codes. They typically are in the range
13328: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
13329: @i{ior}s is -512@minus{}@i{errno}.
13330: 
13331: @end table
13332: 
13333: @c =====================================================================
13334: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13335: @section The optional Programming-Tools word set
13336: @c =====================================================================
13337: @cindex system documentation, programming-tools words
13338: @cindex programming-tools words, system documentation
13339: 
13340: @menu
13341: * programming-idef::            Implementation Defined Options            
13342: * programming-ambcond::         Ambiguous Conditions         
13343: @end menu
13344: 
13345: 
13346: @c ---------------------------------------------------------------------
13347: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13348: @subsection Implementation Defined Options
13349: @c ---------------------------------------------------------------------
13350: @cindex implementation-defined options, programming-tools words
13351: @cindex programming-tools words, implementation-defined options
13352: 
13353: @table @i
13354: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13355: @cindex @code{;CODE} ending sequence
13356: @cindex @code{CODE} ending sequence
13357: @code{END-CODE}
13358: 
13359: @item manner of processing input following @code{;CODE} and @code{CODE}:
13360: @cindex @code{;CODE}, processing input
13361: @cindex @code{CODE}, processing input
13362: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13363: the input is processed by the text interpreter, (starting) in interpret
13364: state.
13365: 
13366: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13367: @cindex @code{ASSEMBLER}, search order capability
13368: The ANS Forth search order word set.
13369: 
13370: @item source and format of display by @code{SEE}:
13371: @cindex @code{SEE}, source and format of output
13372: The source for @code{see} is the executable code used by the inner
13373: interpreter.  The current @code{see} tries to output Forth source code
13374: (and on some platforms, assembly code for primitives) as well as
13375: possible.
13376: 
13377: @end table
13378: 
13379: @c ---------------------------------------------------------------------
13380: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
13381: @subsection Ambiguous conditions
13382: @c ---------------------------------------------------------------------
13383: @cindex programming-tools words, ambiguous conditions
13384: @cindex ambiguous conditions, programming-tools words
13385: 
13386: @table @i
13387: 
13388: @item deleting the compilation word list (@code{FORGET}):
13389: @cindex @code{FORGET}, deleting the compilation word list
13390: Not implemented (yet).
13391: 
13392: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13393: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13394: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
13395: @cindex control-flow stack underflow
13396: This typically results in an @code{abort"} with a descriptive error
13397: message (may change into a @code{-22 throw} (Control structure mismatch)
13398: in the future). You may also get a memory access error. If you are
13399: unlucky, this ambiguous condition is not caught.
13400: 
13401: @item @i{name} can't be found (@code{FORGET}):
13402: @cindex @code{FORGET}, @i{name} can't be found
13403: Not implemented (yet).
13404: 
13405: @item @i{name} not defined via @code{CREATE}:
13406: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
13407: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13408: the execution semantics of the last defined word no matter how it was
13409: defined.
13410: 
13411: @item @code{POSTPONE} applied to @code{[IF]}:
13412: @cindex @code{POSTPONE} applied to @code{[IF]}
13413: @cindex @code{[IF]} and @code{POSTPONE}
13414: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13415: equivalent to @code{[IF]}.
13416: 
13417: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13418: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13419: Continue in the same state of conditional compilation in the next outer
13420: input source. Currently there is no warning to the user about this.
13421: 
13422: @item removing a needed definition (@code{FORGET}):
13423: @cindex @code{FORGET}, removing a needed definition
13424: Not implemented (yet).
13425: 
13426: @end table
13427: 
13428: 
13429: @c =====================================================================
13430: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
13431: @section The optional Search-Order word set
13432: @c =====================================================================
13433: @cindex system documentation, search-order words
13434: @cindex search-order words, system documentation
13435: 
13436: @menu
13437: * search-idef::                 Implementation Defined Options                 
13438: * search-ambcond::              Ambiguous Conditions              
13439: @end menu
13440: 
13441: 
13442: @c ---------------------------------------------------------------------
13443: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13444: @subsection Implementation Defined Options
13445: @c ---------------------------------------------------------------------
13446: @cindex implementation-defined options, search-order words
13447: @cindex search-order words, implementation-defined options
13448: 
13449: @table @i
13450: @item maximum number of word lists in search order:
13451: @cindex maximum number of word lists in search order
13452: @cindex search order, maximum depth
13453: @code{s" wordlists" environment? drop .}. Currently 16.
13454: 
13455: @item minimum search order:
13456: @cindex minimum search order
13457: @cindex search order, minimum
13458: @code{root root}.
13459: 
13460: @end table
13461: 
13462: @c ---------------------------------------------------------------------
13463: @node search-ambcond,  , search-idef, The optional Search-Order word set
13464: @subsection Ambiguous conditions
13465: @c ---------------------------------------------------------------------
13466: @cindex search-order words, ambiguous conditions
13467: @cindex ambiguous conditions, search-order words
13468: 
13469: @table @i
13470: @item changing the compilation word list (during compilation):
13471: @cindex changing the compilation word list (during compilation)
13472: @cindex compilation word list, change before definition ends
13473: The word is entered into the word list that was the compilation word list
13474: at the start of the definition. Any changes to the name field (e.g.,
13475: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13476: are applied to the latest defined word (as reported by @code{latest} or
13477: @code{latestxt}), if possible, irrespective of the compilation word list.
13478: 
13479: @item search order empty (@code{previous}):
13480: @cindex @code{previous}, search order empty
13481: @cindex vocstack empty, @code{previous}
13482: @code{abort" Vocstack empty"}.
13483: 
13484: @item too many word lists in search order (@code{also}):
13485: @cindex @code{also}, too many word lists in search order
13486: @cindex vocstack full, @code{also}
13487: @code{abort" Vocstack full"}.
13488: 
13489: @end table
13490: 
13491: @c ***************************************************************
13492: @node Standard vs Extensions, Model, ANS conformance, Top
13493: @chapter Should I use Gforth extensions?
13494: @cindex Gforth extensions
13495: 
13496: As you read through the rest of this manual, you will see documentation
13497: for @i{Standard} words, and documentation for some appealing Gforth
13498: @i{extensions}. You might ask yourself the question: @i{``Should I
13499: restrict myself to the standard, or should I use the extensions?''}
13500: 
13501: The answer depends on the goals you have for the program you are working
13502: on:
13503: 
13504: @itemize @bullet
13505: 
13506: @item Is it just for yourself or do you want to share it with others?
13507: 
13508: @item
13509: If you want to share it, do the others all use Gforth?
13510: 
13511: @item
13512: If it is just for yourself, do you want to restrict yourself to Gforth?
13513: 
13514: @end itemize
13515: 
13516: If restricting the program to Gforth is ok, then there is no reason not
13517: to use extensions.  It is still a good idea to keep to the standard
13518: where it is easy, in case you want to reuse these parts in another
13519: program that you want to be portable.
13520: 
13521: If you want to be able to port the program to other Forth systems, there
13522: are the following points to consider:
13523: 
13524: @itemize @bullet
13525: 
13526: @item
13527: Most Forth systems that are being maintained support the ANS Forth
13528: standard.  So if your program complies with the standard, it will be
13529: portable among many systems.
13530: 
13531: @item
13532: A number of the Gforth extensions can be implemented in ANS Forth using
13533: public-domain files provided in the @file{compat/} directory. These are
13534: mentioned in the text in passing.  There is no reason not to use these
13535: extensions, your program will still be ANS Forth compliant; just include
13536: the appropriate compat files with your program.
13537: 
13538: @item
13539: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13540: analyse your program and determine what non-Standard words it relies
13541: upon.  However, it does not check whether you use standard words in a
13542: non-standard way.
13543: 
13544: @item
13545: Some techniques are not standardized by ANS Forth, and are hard or
13546: impossible to implement in a standard way, but can be implemented in
13547: most Forth systems easily, and usually in similar ways (e.g., accessing
13548: word headers).  Forth has a rich historical precedent for programmers
13549: taking advantage of implementation-dependent features of their tools
13550: (for example, relying on a knowledge of the dictionary
13551: structure). Sometimes these techniques are necessary to extract every
13552: last bit of performance from the hardware, sometimes they are just a
13553: programming shorthand.
13554: 
13555: @item
13556: Does using a Gforth extension save more work than the porting this part
13557: to other Forth systems (if any) will cost?
13558: 
13559: @item
13560: Is the additional functionality worth the reduction in portability and
13561: the additional porting problems?
13562: 
13563: @end itemize
13564: 
13565: In order to perform these consideratios, you need to know what's
13566: standard and what's not.  This manual generally states if something is
13567: non-standard, but the authoritative source is the
13568: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
13569: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13570: into the thought processes of the technical committee.
13571: 
13572: Note also that portability between Forth systems is not the only
13573: portability issue; there is also the issue of portability between
13574: different platforms (processor/OS combinations).
13575: 
13576: @c ***************************************************************
13577: @node Model, Integrating Gforth, Standard vs Extensions, Top
13578: @chapter Model
13579: 
13580: This chapter has yet to be written. It will contain information, on
13581: which internal structures you can rely.
13582: 
13583: @c ***************************************************************
13584: @node Integrating Gforth, Emacs and Gforth, Model, Top
13585: @chapter Integrating Gforth into C programs
13586: 
13587: This is not yet implemented.
13588: 
13589: Several people like to use Forth as scripting language for applications
13590: that are otherwise written in C, C++, or some other language.
13591: 
13592: The Forth system ATLAST provides facilities for embedding it into
13593: applications; unfortunately it has several disadvantages: most
13594: importantly, it is not based on ANS Forth, and it is apparently dead
13595: (i.e., not developed further and not supported). The facilities
13596: provided by Gforth in this area are inspired by ATLAST's facilities, so
13597: making the switch should not be hard.
13598: 
13599: We also tried to design the interface such that it can easily be
13600: implemented by other Forth systems, so that we may one day arrive at a
13601: standardized interface. Such a standard interface would allow you to
13602: replace the Forth system without having to rewrite C code.
13603: 
13604: You embed the Gforth interpreter by linking with the library
13605: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
13606: global symbols in this library that belong to the interface, have the
13607: prefix @code{forth_}. (Global symbols that are used internally have the
13608: prefix @code{gforth_}).
13609: 
13610: You can include the declarations of Forth types and the functions and
13611: variables of the interface with @code{#include <forth.h>}.
13612: 
13613: Types.
13614: 
13615: Variables.
13616: 
13617: Data and FP Stack pointer. Area sizes.
13618: 
13619: functions.
13620: 
13621: forth_init(imagefile)
13622: forth_evaluate(string) exceptions?
13623: forth_goto(address) (or forth_execute(xt)?)
13624: forth_continue() (a corountining mechanism)
13625: 
13626: Adding primitives.
13627: 
13628: No checking.
13629: 
13630: Signals?
13631: 
13632: Accessing the Stacks
13633: 
13634: @c ******************************************************************
13635: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13636: @chapter Emacs and Gforth
13637: @cindex Emacs and Gforth
13638: 
13639: @cindex @file{gforth.el}
13640: @cindex @file{forth.el}
13641: @cindex Rydqvist, Goran
13642: @cindex Kuehling, David
13643: @cindex comment editing commands
13644: @cindex @code{\}, editing with Emacs
13645: @cindex debug tracer editing commands
13646: @cindex @code{~~}, removal with Emacs
13647: @cindex Forth mode in Emacs
13648: 
13649: Gforth comes with @file{gforth.el}, an improved version of
13650: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
13651: improvements are:
13652: 
13653: @itemize @bullet
13654: @item
13655: A better handling of indentation.
13656: @item
13657: A custom hilighting engine for Forth-code.
13658: @item
13659: Comment paragraph filling (@kbd{M-q})
13660: @item
13661: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13662: @item
13663: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
13664: @item
13665: Support of the @code{info-lookup} feature for looking up the
13666: documentation of a word.
13667: @item
13668: Support for reading and writing blocks files.
13669: @end itemize
13670: 
13671: To get a basic description of these features, enter Forth mode and
13672: type @kbd{C-h m}.
13673: 
13674: @cindex source location of error or debugging output in Emacs
13675: @cindex error output, finding the source location in Emacs
13676: @cindex debugging output, finding the source location in Emacs
13677: In addition, Gforth supports Emacs quite well: The source code locations
13678: given in error messages, debugging output (from @code{~~}) and failed
13679: assertion messages are in the right format for Emacs' compilation mode
13680: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13681: Manual}) so the source location corresponding to an error or other
13682: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13683: @kbd{C-c C-c} for the error under the cursor).
13684: 
13685: @cindex viewing the documentation of a word in Emacs
13686: @cindex context-sensitive help
13687: Moreover, for words documented in this manual, you can look up the
13688: glossary entry quickly by using @kbd{C-h TAB}
13689: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13690: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
13691: later and does not work for words containing @code{:}.
13692: 
13693: @menu
13694: * Installing gforth.el::        Making Emacs aware of Forth.
13695: * Emacs Tags::                  Viewing the source of a word in Emacs.
13696: * Hilighting::                  Making Forth code look prettier.
13697: * Auto-Indentation::            Customizing auto-indentation.
13698: * Blocks Files::                Reading and writing blocks files.
13699: @end menu
13700: 
13701: @c ----------------------------------
13702: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
13703: @section Installing gforth.el
13704: @cindex @file{.emacs}
13705: @cindex @file{gforth.el}, installation
13706: To make the features from @file{gforth.el} available in Emacs, add
13707: the following lines to your @file{.emacs} file:
13708: 
13709: @example
13710: (autoload 'forth-mode "gforth.el")
13711: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
13712: 			    auto-mode-alist))
13713: (autoload 'forth-block-mode "gforth.el")
13714: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
13715: 			    auto-mode-alist))
13716: (add-hook 'forth-mode-hook (function (lambda ()
13717:    ;; customize variables here:
13718:    (setq forth-indent-level 4)
13719:    (setq forth-minor-indent-level 2)
13720:    (setq forth-hilight-level 3)
13721:    ;;; ...
13722: )))
13723: @end example
13724: 
13725: @c ----------------------------------
13726: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13727: @section Emacs Tags
13728: @cindex @file{TAGS} file
13729: @cindex @file{etags.fs}
13730: @cindex viewing the source of a word in Emacs
13731: @cindex @code{require}, placement in files
13732: @cindex @code{include}, placement in files
13733: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13734: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
13735: contains the definitions of all words defined afterwards. You can then
13736: find the source for a word using @kbd{M-.}. Note that Emacs can use
13737: several tags files at the same time (e.g., one for the Gforth sources
13738: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13739: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13740: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
13741: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
13742: with @file{etags.fs}, you should avoid putting definitions both before
13743: and after @code{require} etc., otherwise you will see the same file
13744: visited several times by commands like @code{tags-search}.
13745: 
13746: @c ----------------------------------
13747: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13748: @section Hilighting
13749: @cindex hilighting Forth code in Emacs
13750: @cindex highlighting Forth code in Emacs
13751: @file{gforth.el} comes with a custom source hilighting engine.  When
13752: you open a file in @code{forth-mode}, it will be completely parsed,
13753: assigning faces to keywords, comments, strings etc.  While you edit
13754: the file, modified regions get parsed and updated on-the-fly. 
13755: 
13756: Use the variable `forth-hilight-level' to change the level of
13757: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
13758: you set the hilighting level to 0, the parser will still work in the
13759: background, collecting information about whether regions of text are
13760: ``compiled'' or ``interpreted''.  Those information are required for
13761: auto-indentation to work properly.  Set `forth-disable-parser' to
13762: non-nil if your computer is too slow to handle parsing.  This will
13763: have an impact on the smartness of the auto-indentation engine,
13764: though.
13765: 
13766: Sometimes Forth sources define new features that should be hilighted,
13767: new control structures, defining-words etc.  You can use the variable
13768: `forth-custom-words' to make @code{forth-mode} hilight additional
13769: words and constructs.  See the docstring of `forth-words' for details
13770: (in Emacs, type @kbd{C-h v forth-words}).
13771: 
13772: `forth-custom-words' is meant to be customized in your
13773: @file{.emacs} file.  To customize hilighing in a file-specific manner,
13774: set `forth-local-words' in a local-variables section at the end of
13775: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13776: 
13777: Example:
13778: @example
13779: 0 [IF]
13780:    Local Variables:
13781:    forth-local-words:
13782:       ((("t:") definition-starter (font-lock-keyword-face . 1)
13783:         "[ \t\n]" t name (font-lock-function-name-face . 3))
13784:        ((";t") definition-ender (font-lock-keyword-face . 1)))
13785:    End:
13786: [THEN]
13787: @end example
13788: 
13789: @c ----------------------------------
13790: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13791: @section Auto-Indentation
13792: @cindex auto-indentation of Forth code in Emacs
13793: @cindex indentation of Forth code in Emacs
13794: @code{forth-mode} automatically tries to indent lines in a smart way,
13795: whenever you type @key{TAB} or break a line with @kbd{C-m}.
13796: 
13797: Simple customization can be achieved by setting
13798: `forth-indent-level' and `forth-minor-indent-level' in your
13799: @file{.emacs} file. For historical reasons @file{gforth.el} indents
13800: per default by multiples of 4 columns.  To use the more traditional
13801: 3-column indentation, add the following lines to your @file{.emacs}:
13802: 
13803: @example
13804: (add-hook 'forth-mode-hook (function (lambda ()
13805:    ;; customize variables here:
13806:    (setq forth-indent-level 3)
13807:    (setq forth-minor-indent-level 1)
13808: )))
13809: @end example
13810: 
13811: If you want indentation to recognize non-default words, customize it
13812: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
13813: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
13814: v forth-indent-words}).
13815: 
13816: To customize indentation in a file-specific manner, set
13817: `forth-local-indent-words' in a local-variables section at the end of
13818: your source file (@pxref{Local Variables in Files, Variables,,emacs,
13819: Emacs Manual}).
13820: 
13821: Example:
13822: @example
13823: 0 [IF]
13824:    Local Variables:
13825:    forth-local-indent-words:
13826:       ((("t:") (0 . 2) (0 . 2))
13827:        ((";t") (-2 . 0) (0 . -2)))
13828:    End:
13829: [THEN]
13830: @end example
13831: 
13832: @c ----------------------------------
13833: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
13834: @section Blocks Files
13835: @cindex blocks files, use with Emacs
13836: @code{forth-mode} Autodetects blocks files by checking whether the
13837: length of the first line exceeds 1023 characters.  It then tries to
13838: convert the file into normal text format.  When you save the file, it
13839: will be written to disk as normal stream-source file.
13840: 
13841: If you want to write blocks files, use @code{forth-blocks-mode}.  It
13842: inherits all the features from @code{forth-mode}, plus some additions:
13843: 
13844: @itemize @bullet
13845: @item
13846: Files are written to disk in blocks file format.
13847: @item
13848: Screen numbers are displayed in the mode line (enumerated beginning
13849: with the value of `forth-block-base')
13850: @item
13851: Warnings are displayed when lines exceed 64 characters.
13852: @item
13853: The beginning of the currently edited block is marked with an
13854: overlay-arrow. 
13855: @end itemize
13856: 
13857: There are some restrictions you should be aware of.  When you open a
13858: blocks file that contains tabulator or newline characters, these
13859: characters will be translated into spaces when the file is written
13860: back to disk.  If tabs or newlines are encountered during blocks file
13861: reading, an error is output to the echo area. So have a look at the
13862: `*Messages*' buffer, when Emacs' bell rings during reading.
13863: 
13864: Please consult the docstring of @code{forth-blocks-mode} for more
13865: information by typing @kbd{C-h v forth-blocks-mode}).
13866: 
13867: @c ******************************************************************
13868: @node Image Files, Engine, Emacs and Gforth, Top
13869: @chapter Image Files
13870: @cindex image file
13871: @cindex @file{.fi} files
13872: @cindex precompiled Forth code
13873: @cindex dictionary in persistent form
13874: @cindex persistent form of dictionary
13875: 
13876: An image file is a file containing an image of the Forth dictionary,
13877: i.e., compiled Forth code and data residing in the dictionary.  By
13878: convention, we use the extension @code{.fi} for image files.
13879: 
13880: @menu
13881: * Image Licensing Issues::      Distribution terms for images.
13882: * Image File Background::       Why have image files?
13883: * Non-Relocatable Image Files::  don't always work.
13884: * Data-Relocatable Image Files::  are better.
13885: * Fully Relocatable Image Files::  better yet.
13886: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
13887: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
13888: * Modifying the Startup Sequence::  and turnkey applications.
13889: @end menu
13890: 
13891: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13892: @section Image Licensing Issues
13893: @cindex license for images
13894: @cindex image license
13895: 
13896: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13897: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13898: original image; i.e., according to copyright law it is a derived work of
13899: the original image.
13900: 
13901: Since Gforth is distributed under the GNU GPL, the newly created image
13902: falls under the GNU GPL, too. In particular, this means that if you
13903: distribute the image, you have to make all of the sources for the image
13904: available, including those you wrote.  For details see @ref{Copying, ,
13905: GNU General Public License (Section 3)}.
13906: 
13907: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13908: contains only code compiled from the sources you gave it; if none of
13909: these sources is under the GPL, the terms discussed above do not apply
13910: to the image. However, if your image needs an engine (a gforth binary)
13911: that is under the GPL, you should make sure that you distribute both in
13912: a way that is at most a @emph{mere aggregation}, if you don't want the
13913: terms of the GPL to apply to the image.
13914: 
13915: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
13916: @section Image File Background
13917: @cindex image file background
13918: 
13919: Gforth consists not only of primitives (in the engine), but also of
13920: definitions written in Forth. Since the Forth compiler itself belongs to
13921: those definitions, it is not possible to start the system with the
13922: engine and the Forth source alone. Therefore we provide the Forth
13923: code as an image file in nearly executable form. When Gforth starts up,
13924: a C routine loads the image file into memory, optionally relocates the
13925: addresses, then sets up the memory (stacks etc.) according to
13926: information in the image file, and (finally) starts executing Forth
13927: code.
13928: 
13929: The image file variants represent different compromises between the
13930: goals of making it easy to generate image files and making them
13931: portable.
13932: 
13933: @cindex relocation at run-time
13934: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
13935: run-time. This avoids many of the complications discussed below (image
13936: files are data relocatable without further ado), but costs performance
13937: (one addition per memory access).
13938: 
13939: @cindex relocation at load-time
13940: By contrast, the Gforth loader performs relocation at image load time. The
13941: loader also has to replace tokens that represent primitive calls with the
13942: appropriate code-field addresses (or code addresses in the case of
13943: direct threading).
13944: 
13945: There are three kinds of image files, with different degrees of
13946: relocatability: non-relocatable, data-relocatable, and fully relocatable
13947: image files.
13948: 
13949: @cindex image file loader
13950: @cindex relocating loader
13951: @cindex loader for image files
13952: These image file variants have several restrictions in common; they are
13953: caused by the design of the image file loader:
13954: 
13955: @itemize @bullet
13956: @item
13957: There is only one segment; in particular, this means, that an image file
13958: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
13959: them). The contents of the stacks are not represented, either.
13960: 
13961: @item
13962: The only kinds of relocation supported are: adding the same offset to
13963: all cells that represent data addresses; and replacing special tokens
13964: with code addresses or with pieces of machine code.
13965: 
13966: If any complex computations involving addresses are performed, the
13967: results cannot be represented in the image file. Several applications that
13968: use such computations come to mind:
13969: @itemize @minus
13970: @item
13971: Hashing addresses (or data structures which contain addresses) for table
13972: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13973: purpose, you will have no problem, because the hash tables are
13974: recomputed automatically when the system is started. If you use your own
13975: hash tables, you will have to do something similar.
13976: 
13977: @item
13978: There's a cute implementation of doubly-linked lists that uses
13979: @code{XOR}ed addresses. You could represent such lists as singly-linked
13980: in the image file, and restore the doubly-linked representation on
13981: startup.@footnote{In my opinion, though, you should think thrice before
13982: using a doubly-linked list (whatever implementation).}
13983: 
13984: @item
13985: The code addresses of run-time routines like @code{docol:} cannot be
13986: represented in the image file (because their tokens would be replaced by
13987: machine code in direct threaded implementations). As a workaround,
13988: compute these addresses at run-time with @code{>code-address} from the
13989: executions tokens of appropriate words (see the definitions of
13990: @code{docol:} and friends in @file{kernel/getdoers.fs}).
13991: 
13992: @item
13993: On many architectures addresses are represented in machine code in some
13994: shifted or mangled form. You cannot put @code{CODE} words that contain
13995: absolute addresses in this form in a relocatable image file. Workarounds
13996: are representing the address in some relative form (e.g., relative to
13997: the CFA, which is present in some register), or loading the address from
13998: a place where it is stored in a non-mangled form.
13999: @end itemize
14000: @end itemize
14001: 
14002: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14003: @section Non-Relocatable Image Files
14004: @cindex non-relocatable image files
14005: @cindex image file, non-relocatable
14006: 
14007: These files are simple memory dumps of the dictionary. They are specific
14008: to the executable (i.e., @file{gforth} file) they were created
14009: with. What's worse, they are specific to the place on which the
14010: dictionary resided when the image was created. Now, there is no
14011: guarantee that the dictionary will reside at the same place the next
14012: time you start Gforth, so there's no guarantee that a non-relocatable
14013: image will work the next time (Gforth will complain instead of crashing,
14014: though).
14015: 
14016: You can create a non-relocatable image file with
14017: 
14018: 
14019: doc-savesystem
14020: 
14021: 
14022: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14023: @section Data-Relocatable Image Files
14024: @cindex data-relocatable image files
14025: @cindex image file, data-relocatable
14026: 
14027: These files contain relocatable data addresses, but fixed code addresses
14028: (instead of tokens). They are specific to the executable (i.e.,
14029: @file{gforth} file) they were created with. For direct threading on some
14030: architectures (e.g., the i386), data-relocatable images do not work. You
14031: get a data-relocatable image, if you use @file{gforthmi} with a
14032: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14033: Relocatable Image Files}).
14034: 
14035: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14036: @section Fully Relocatable Image Files
14037: @cindex fully relocatable image files
14038: @cindex image file, fully relocatable
14039: 
14040: @cindex @file{kern*.fi}, relocatability
14041: @cindex @file{gforth.fi}, relocatability
14042: These image files have relocatable data addresses, and tokens for code
14043: addresses. They can be used with different binaries (e.g., with and
14044: without debugging) on the same machine, and even across machines with
14045: the same data formats (byte order, cell size, floating point
14046: format). However, they are usually specific to the version of Gforth
14047: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14048: are fully relocatable.
14049: 
14050: There are two ways to create a fully relocatable image file:
14051: 
14052: @menu
14053: * gforthmi::                    The normal way
14054: * cross.fs::                    The hard way
14055: @end menu
14056: 
14057: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14058: @subsection @file{gforthmi}
14059: @cindex @file{comp-i.fs}
14060: @cindex @file{gforthmi}
14061: 
14062: You will usually use @file{gforthmi}. If you want to create an
14063: image @i{file} that contains everything you would load by invoking
14064: Gforth with @code{gforth @i{options}}, you simply say:
14065: @example
14066: gforthmi @i{file} @i{options}
14067: @end example
14068: 
14069: E.g., if you want to create an image @file{asm.fi} that has the file
14070: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14071: like this:
14072: 
14073: @example
14074: gforthmi asm.fi asm.fs
14075: @end example
14076: 
14077: @file{gforthmi} is implemented as a sh script and works like this: It
14078: produces two non-relocatable images for different addresses and then
14079: compares them. Its output reflects this: first you see the output (if
14080: any) of the two Gforth invocations that produce the non-relocatable image
14081: files, then you see the output of the comparing program: It displays the
14082: offset used for data addresses and the offset used for code addresses;
14083: moreover, for each cell that cannot be represented correctly in the
14084: image files, it displays a line like this:
14085: 
14086: @example
14087:      78DC         BFFFFA50         BFFFFA40
14088: @end example
14089: 
14090: This means that at offset $78dc from @code{forthstart}, one input image
14091: contains $bffffa50, and the other contains $bffffa40. Since these cells
14092: cannot be represented correctly in the output image, you should examine
14093: these places in the dictionary and verify that these cells are dead
14094: (i.e., not read before they are written).
14095: 
14096: @cindex --application, @code{gforthmi} option
14097: If you insert the option @code{--application} in front of the image file
14098: name, you will get an image that uses the @code{--appl-image} option
14099: instead of the @code{--image-file} option (@pxref{Invoking
14100: Gforth}). When you execute such an image on Unix (by typing the image
14101: name as command), the Gforth engine will pass all options to the image
14102: instead of trying to interpret them as engine options.
14103: 
14104: If you type @file{gforthmi} with no arguments, it prints some usage
14105: instructions.
14106: 
14107: @cindex @code{savesystem} during @file{gforthmi}
14108: @cindex @code{bye} during @file{gforthmi}
14109: @cindex doubly indirect threaded code
14110: @cindex environment variables
14111: @cindex @code{GFORTHD} -- environment variable
14112: @cindex @code{GFORTH} -- environment variable
14113: @cindex @code{gforth-ditc}
14114: There are a few wrinkles: After processing the passed @i{options}, the
14115: words @code{savesystem} and @code{bye} must be visible. A special doubly
14116: indirect threaded version of the @file{gforth} executable is used for
14117: creating the non-relocatable images; you can pass the exact filename of
14118: this executable through the environment variable @code{GFORTHD}
14119: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14120: indirect threaded, you will not get a fully relocatable image, but a
14121: data-relocatable image (because there is no code address offset). The
14122: normal @file{gforth} executable is used for creating the relocatable
14123: image; you can pass the exact filename of this executable through the
14124: environment variable @code{GFORTH}.
14125: 
14126: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
14127: @subsection @file{cross.fs}
14128: @cindex @file{cross.fs}
14129: @cindex cross-compiler
14130: @cindex metacompiler
14131: @cindex target compiler
14132: 
14133: You can also use @code{cross}, a batch compiler that accepts a Forth-like
14134: programming language (@pxref{Cross Compiler}).
14135: 
14136: @code{cross} allows you to create image files for machines with
14137: different data sizes and data formats than the one used for generating
14138: the image file. You can also use it to create an application image that
14139: does not contain a Forth compiler. These features are bought with
14140: restrictions and inconveniences in programming. E.g., addresses have to
14141: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14142: order to make the code relocatable.
14143: 
14144: 
14145: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14146: @section Stack and Dictionary Sizes
14147: @cindex image file, stack and dictionary sizes
14148: @cindex dictionary size default
14149: @cindex stack size default
14150: 
14151: If you invoke Gforth with a command line flag for the size
14152: (@pxref{Invoking Gforth}), the size you specify is stored in the
14153: dictionary. If you save the dictionary with @code{savesystem} or create
14154: an image with @file{gforthmi}, this size will become the default
14155: for the resulting image file. E.g., the following will create a
14156: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
14157: 
14158: @example
14159: gforthmi gforth.fi -m 1M
14160: @end example
14161: 
14162: In other words, if you want to set the default size for the dictionary
14163: and the stacks of an image, just invoke @file{gforthmi} with the
14164: appropriate options when creating the image.
14165: 
14166: @cindex stack size, cache-friendly
14167: Note: For cache-friendly behaviour (i.e., good performance), you should
14168: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14169: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14170: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14171: 
14172: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14173: @section Running Image Files
14174: @cindex running image files
14175: @cindex invoking image files
14176: @cindex image file invocation
14177: 
14178: @cindex -i, invoke image file
14179: @cindex --image file, invoke image file
14180: You can invoke Gforth with an image file @i{image} instead of the
14181: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14182: @example
14183: gforth -i @i{image}
14184: @end example
14185: 
14186: @cindex executable image file
14187: @cindex image file, executable
14188: If your operating system supports starting scripts with a line of the
14189: form @code{#! ...}, you just have to type the image file name to start
14190: Gforth with this image file (note that the file extension @code{.fi} is
14191: just a convention). I.e., to run Gforth with the image file @i{image},
14192: you can just type @i{image} instead of @code{gforth -i @i{image}}.
14193: This works because every @code{.fi} file starts with a line of this
14194: format:
14195: 
14196: @example
14197: #! /usr/local/bin/gforth-0.4.0 -i
14198: @end example
14199: 
14200: The file and pathname for the Gforth engine specified on this line is
14201: the specific Gforth executable that it was built against; i.e. the value
14202: of the environment variable @code{GFORTH} at the time that
14203: @file{gforthmi} was executed.
14204: 
14205: You can make use of the same shell capability to make a Forth source
14206: file into an executable. For example, if you place this text in a file:
14207: 
14208: @example
14209: #! /usr/local/bin/gforth
14210: 
14211: ." Hello, world" CR
14212: bye
14213: @end example
14214: 
14215: @noindent
14216: and then make the file executable (chmod +x in Unix), you can run it
14217: directly from the command line. The sequence @code{#!} is used in two
14218: ways; firstly, it is recognised as a ``magic sequence'' by the operating
14219: system@footnote{The Unix kernel actually recognises two types of files:
14220: executable files and files of data, where the data is processed by an
14221: interpreter that is specified on the ``interpreter line'' -- the first
14222: line of the file, starting with the sequence #!. There may be a small
14223: limit (e.g., 32) on the number of characters that may be specified on
14224: the interpreter line.} secondly it is treated as a comment character by
14225: Gforth. Because of the second usage, a space is required between
14226: @code{#!} and the path to the executable (moreover, some Unixes
14227: require the sequence @code{#! /}).
14228: 
14229: The disadvantage of this latter technique, compared with using
14230: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14231: compiled on-the-fly, each time the program is invoked.
14232: 
14233: doc-#!
14234: 
14235: 
14236: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
14237: @section Modifying the Startup Sequence
14238: @cindex startup sequence for image file
14239: @cindex image file initialization sequence
14240: @cindex initialization sequence of image file
14241: 
14242: You can add your own initialization to the startup sequence through the
14243: deferred word @code{'cold}. @code{'cold} is invoked just before the
14244: image-specific command line processing (i.e., loading files and
14245: evaluating (@code{-e}) strings) starts.
14246: 
14247: A sequence for adding your initialization usually looks like this:
14248: 
14249: @example
14250: :noname
14251:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14252:     ... \ your stuff
14253: ; IS 'cold
14254: @end example
14255: 
14256: @cindex turnkey image files
14257: @cindex image file, turnkey applications
14258: You can make a turnkey image by letting @code{'cold} execute a word
14259: (your turnkey application) that never returns; instead, it exits Gforth
14260: via @code{bye} or @code{throw}.
14261: 
14262: @cindex command-line arguments, access
14263: @cindex arguments on the command line, access
14264: You can access the (image-specific) command-line arguments through the
14265: variables @code{argc} and @code{argv}. @code{arg} provides convenient
14266: access to @code{argv}.
14267: 
14268: If @code{'cold} exits normally, Gforth processes the command-line
14269: arguments as files to be loaded and strings to be evaluated.  Therefore,
14270: @code{'cold} should remove the arguments it has used in this case.
14271: 
14272: 
14273: 
14274: doc-'cold
14275: doc-argc
14276: doc-argv
14277: doc-arg
14278: 
14279: 
14280: 
14281: @c ******************************************************************
14282: @node Engine, Cross Compiler, Image Files, Top
14283: @chapter Engine
14284: @cindex engine
14285: @cindex virtual machine
14286: 
14287: Reading this chapter is not necessary for programming with Gforth. It
14288: may be helpful for finding your way in the Gforth sources.
14289: 
14290: The ideas in this section have also been published in the following
14291: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14292: Forth-Tagung '93; M. Anton Ertl,
14293: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14294: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14295: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14296: Threaded code variations and optimizations (extended version)}},
14297: Forth-Tagung '02.
14298: 
14299: @menu
14300: * Portability::                 
14301: * Threading::                   
14302: * Primitives::                  
14303: * Performance::                 
14304: @end menu
14305: 
14306: @node Portability, Threading, Engine, Engine
14307: @section Portability
14308: @cindex engine portability
14309: 
14310: An important goal of the Gforth Project is availability across a wide
14311: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14312: achieved this goal by manually coding the engine in assembly language
14313: for several then-popular processors. This approach is very
14314: labor-intensive and the results are short-lived due to progress in
14315: computer architecture.
14316: 
14317: @cindex C, using C for the engine
14318: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14319: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14320: particularly popular for UNIX-based Forths due to the large variety of
14321: architectures of UNIX machines. Unfortunately an implementation in C
14322: does not mix well with the goals of efficiency and with using
14323: traditional techniques: Indirect or direct threading cannot be expressed
14324: in C, and switch threading, the fastest technique available in C, is
14325: significantly slower. Another problem with C is that it is very
14326: cumbersome to express double integer arithmetic.
14327: 
14328: @cindex GNU C for the engine
14329: @cindex long long
14330: Fortunately, there is a portable language that does not have these
14331: limitations: GNU C, the version of C processed by the GNU C compiler
14332: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14333: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14334: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14335: threading possible, its @code{long long} type (@pxref{Long Long, ,
14336: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
14337: double numbers on many systems.  GNU C is freely available on all
14338: important (and many unimportant) UNIX machines, VMS, 80386s running
14339: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14340: on all these machines.
14341: 
14342: Writing in a portable language has the reputation of producing code that
14343: is slower than assembly. For our Forth engine we repeatedly looked at
14344: the code produced by the compiler and eliminated most compiler-induced
14345: inefficiencies by appropriate changes in the source code.
14346: 
14347: @cindex explicit register declarations
14348: @cindex --enable-force-reg, configuration flag
14349: @cindex -DFORCE_REG
14350: However, register allocation cannot be portably influenced by the
14351: programmer, leading to some inefficiencies on register-starved
14352: machines. We use explicit register declarations (@pxref{Explicit Reg
14353: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14354: improve the speed on some machines. They are turned on by using the
14355: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14356: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14357: machine, but also on the compiler version: On some machines some
14358: compiler versions produce incorrect code when certain explicit register
14359: declarations are used. So by default @code{-DFORCE_REG} is not used.
14360: 
14361: @node Threading, Primitives, Portability, Engine
14362: @section Threading
14363: @cindex inner interpreter implementation
14364: @cindex threaded code implementation
14365: 
14366: @cindex labels as values
14367: GNU C's labels as values extension (available since @code{gcc-2.0},
14368: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
14369: makes it possible to take the address of @i{label} by writing
14370: @code{&&@i{label}}.  This address can then be used in a statement like
14371: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
14372: @code{goto x}.
14373: 
14374: @cindex @code{NEXT}, indirect threaded
14375: @cindex indirect threaded inner interpreter
14376: @cindex inner interpreter, indirect threaded
14377: With this feature an indirect threaded @code{NEXT} looks like:
14378: @example
14379: cfa = *ip++;
14380: ca = *cfa;
14381: goto *ca;
14382: @end example
14383: @cindex instruction pointer
14384: For those unfamiliar with the names: @code{ip} is the Forth instruction
14385: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14386: execution token and points to the code field of the next word to be
14387: executed; The @code{ca} (code address) fetched from there points to some
14388: executable code, e.g., a primitive or the colon definition handler
14389: @code{docol}.
14390: 
14391: @cindex @code{NEXT}, direct threaded
14392: @cindex direct threaded inner interpreter
14393: @cindex inner interpreter, direct threaded
14394: Direct threading is even simpler:
14395: @example
14396: ca = *ip++;
14397: goto *ca;
14398: @end example
14399: 
14400: Of course we have packaged the whole thing neatly in macros called
14401: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
14402: 
14403: @menu
14404: * Scheduling::                  
14405: * Direct or Indirect Threaded?::  
14406: * Dynamic Superinstructions::   
14407: * DOES>::                       
14408: @end menu
14409: 
14410: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14411: @subsection Scheduling
14412: @cindex inner interpreter optimization
14413: 
14414: There is a little complication: Pipelined and superscalar processors,
14415: i.e., RISC and some modern CISC machines can process independent
14416: instructions while waiting for the results of an instruction. The
14417: compiler usually reorders (schedules) the instructions in a way that
14418: achieves good usage of these delay slots. However, on our first tries
14419: the compiler did not do well on scheduling primitives. E.g., for
14420: @code{+} implemented as
14421: @example
14422: n=sp[0]+sp[1];
14423: sp++;
14424: sp[0]=n;
14425: NEXT;
14426: @end example
14427: the @code{NEXT} comes strictly after the other code, i.e., there is
14428: nearly no scheduling. After a little thought the problem becomes clear:
14429: The compiler cannot know that @code{sp} and @code{ip} point to different
14430: addresses (and the version of @code{gcc} we used would not know it even
14431: if it was possible), so it could not move the load of the cfa above the
14432: store to the TOS. Indeed the pointers could be the same, if code on or
14433: very near the top of stack were executed. In the interest of speed we
14434: chose to forbid this probably unused ``feature'' and helped the compiler
14435: in scheduling: @code{NEXT} is divided into several parts:
14436: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14437: like:
14438: @example
14439: NEXT_P0;
14440: n=sp[0]+sp[1];
14441: sp++;
14442: NEXT_P1;
14443: sp[0]=n;
14444: NEXT_P2;
14445: @end example
14446: 
14447: There are various schemes that distribute the different operations of
14448: NEXT between these parts in several ways; in general, different schemes
14449: perform best on different processors.  We use a scheme for most
14450: architectures that performs well for most processors of this
14451: architecture; in the future we may switch to benchmarking and chosing
14452: the scheme on installation time.
14453: 
14454: 
14455: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
14456: @subsection Direct or Indirect Threaded?
14457: @cindex threading, direct or indirect?
14458: 
14459: Threaded forth code consists of references to primitives (simple machine
14460: code routines like @code{+}) and to non-primitives (e.g., colon
14461: definitions, variables, constants); for a specific class of
14462: non-primitives (e.g., variables) there is one code routine (e.g.,
14463: @code{dovar}), but each variable needs a separate reference to its data.
14464: 
14465: Traditionally Forth has been implemented as indirect threaded code,
14466: because this allows to use only one cell to reference a non-primitive
14467: (basically you point to the data, and find the code address there).
14468: 
14469: @cindex primitive-centric threaded code
14470: However, threaded code in Gforth (since 0.6.0) uses two cells for
14471: non-primitives, one for the code address, and one for the data address;
14472: the data pointer is an immediate argument for the virtual machine
14473: instruction represented by the code address.  We call this
14474: @emph{primitive-centric} threaded code, because all code addresses point
14475: to simple primitives.  E.g., for a variable, the code address is for
14476: @code{lit} (also used for integer literals like @code{99}).
14477: 
14478: Primitive-centric threaded code allows us to use (faster) direct
14479: threading as dispatch method, completely portably (direct threaded code
14480: in Gforth before 0.6.0 required architecture-specific code).  It also
14481: eliminates the performance problems related to I-cache consistency that
14482: 386 implementation