File:  [gforth] / gforth / doc / gforth.ds
Revision 1.241: download - view: text, annotated - select for diffs
Wed Nov 28 03:03:30 2012 UTC (9 years ago) by dvdkhlng
Branches: MAIN
CVS tags: HEAD
gforth.ds: properly escape instances of '@' in recently added documentation

    1: \input texinfo   @c -*-texinfo-*-
    2: @comment The source is gforth.ds, from which gforth.texi is generated
    3: 
    4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
    5: @comment 1. x-ref all ambiguous or implementation-defined features?
    6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
    7: @comment 3. words in miscellaneous section need a home.
    8: @comment 4. search for TODO for other minor and major works required.
    9: @comment 5. [rats] change all @var to @i in Forth source so that info
   10: @comment    file looks decent.
   11: @c          Not an improvement IMO - anton
   12: @c          and anyway, this should be taken up
   13: @c          with Karl Berry (the texinfo guy) - anton
   14: @c
   15: @c Karl Berry writes:
   16: @c  If they don't like the all-caps for @var Info output, all I can say is
   17: @c  that it's always been that way, and the usage of all-caps for
   18: @c  metavariables has a long tradition.  I think it's best to just let it be
   19: @c  what it is, for the sake of consistency among manuals.
   20: @c
   21: @comment .. would be useful to have a word that identified all deferred words
   22: @comment should semantics stuff in intro be moved to another section
   23: 
   24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
   25: 
   26: @comment %**start of header (This is for running Texinfo on a region.)
   27: @setfilename gforth.info
   28: @include version.texi
   29: @settitle Gforth Manual
   30: @c @syncodeindex pg cp
   31: 
   32: @macro progstyle {}
   33: Programming style note:
   34: @end macro
   35: 
   36: @macro assignment {}
   37: @table @i
   38: @item Assignment:
   39: @end macro
   40: @macro endassignment {}
   41: @end table
   42: @end macro
   43: 
   44: @comment macros for beautifying glossary entries
   45: @macro GLOSS-START {}
   46: @iftex
   47: @ninerm
   48: @end iftex
   49: @end macro
   50: 
   51: @macro GLOSS-END {}
   52: @iftex
   53: @rm
   54: @end iftex
   55: @end macro
   56: 
   57: @comment %**end of header (This is for running Texinfo on a region.)
   58: @copying
   59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
   60: a fast and portable implementation of the ANS Forth language.  It
   61: serves as reference manual, but it also contains an introduction to
   62: Forth and a Forth tutorial.
   63: 
   64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008,2009,2010,2011 Free Software Foundation, Inc.
   65: 
   66: @quotation
   67: Permission is granted to copy, distribute and/or modify this document
   68: under the terms of the GNU Free Documentation License, Version 1.1 or
   69: any later version published by the Free Software Foundation; with no
   70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
   71: and with the Back-Cover Texts as in (a) below.  A copy of the
   72: license is included in the section entitled ``GNU Free Documentation
   73: License.''
   74: 
   75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
   76: this GNU Manual, like GNU software.  Copies published by the Free
   77: Software Foundation raise funds for GNU development.''
   78: @end quotation
   79: @end copying
   80: 
   81: @dircategory Software development
   82: @direntry
   83: * Gforth: (gforth).             A fast interpreter for the Forth language.
   84: @end direntry
   85: @c The Texinfo manual also recommends doing this, but for Gforth it may
   86: @c  not make much sense
   87: @c @dircategory Individual utilities
   88: @c @direntry
   89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
   90: @c @end direntry
   91: 
   92: @titlepage
   93: @title Gforth
   94: @subtitle for version @value{VERSION}, @value{UPDATED}
   95: @author Neal Crook
   96: @author Anton Ertl
   97: @author David Kuehling
   98: @author Bernd Paysan
   99: @author Jens Wilke
  100: @page
  101: @vskip 0pt plus 1filll
  102: @insertcopying
  103: @end titlepage
  104: 
  105: @contents
  106: 
  107: @ifnottex
  108: @node Top, Goals, (dir), (dir)
  109: @top Gforth
  110: 
  111: @insertcopying
  112: @end ifnottex
  113: 
  114: @menu
  115: * Goals::                       About the Gforth Project
  116: * Gforth Environment::          Starting (and exiting) Gforth
  117: * Tutorial::                    Hands-on Forth Tutorial
  118: * Introduction::                An introduction to ANS Forth
  119: * Words::                       Forth words available in Gforth
  120: * Error messages::              How to interpret them
  121: * Tools::                       Programming tools
  122: * ANS conformance::             Implementation-defined options etc.
  123: * Standard vs Extensions::      Should I use extensions?
  124: * Model::                       The abstract machine of Gforth
  125: * Integrating Gforth::          Forth as scripting language for applications
  126: * Emacs and Gforth::            The Gforth Mode
  127: * Image Files::                 @code{.fi} files contain compiled code
  128: * Engine::                      The inner interpreter and the primitives
  129: * Cross Compiler::              The Cross Compiler
  130: * Bugs::                        How to report them
  131: * Origin::                      Authors and ancestors of Gforth
  132: * Forth-related information::   Books and places to look on the WWW
  133: * Licenses::                    
  134: * Word Index::                  An item for each Forth word
  135: * Concept Index::               A menu covering many topics
  136: 
  137: @detailmenu
  138:  --- The Detailed Node Listing ---
  139: 
  140: Gforth Environment
  141: 
  142: * Invoking Gforth::             Getting in
  143: * Leaving Gforth::              Getting out
  144: * Command-line editing::        
  145: * Environment variables::       that affect how Gforth starts up
  146: * Gforth Files::                What gets installed and where
  147: * Gforth in pipes::             
  148: * Startup speed::               When 14ms is not fast enough ...
  149: 
  150: Forth Tutorial
  151: 
  152: * Starting Gforth Tutorial::    
  153: * Syntax Tutorial::             
  154: * Crash Course Tutorial::       
  155: * Stack Tutorial::              
  156: * Arithmetics Tutorial::        
  157: * Stack Manipulation Tutorial::  
  158: * Using files for Forth code Tutorial::  
  159: * Comments Tutorial::           
  160: * Colon Definitions Tutorial::  
  161: * Decompilation Tutorial::      
  162: * Stack-Effect Comments Tutorial::  
  163: * Types Tutorial::              
  164: * Factoring Tutorial::          
  165: * Designing the stack effect Tutorial::  
  166: * Local Variables Tutorial::    
  167: * Conditional execution Tutorial::  
  168: * Flags and Comparisons Tutorial::  
  169: * General Loops Tutorial::      
  170: * Counted loops Tutorial::      
  171: * Recursion Tutorial::          
  172: * Leaving definitions or loops Tutorial::  
  173: * Return Stack Tutorial::       
  174: * Memory Tutorial::             
  175: * Characters and Strings Tutorial::  
  176: * Alignment Tutorial::          
  177: * Floating Point Tutorial::     
  178: * Files Tutorial::              
  179: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
  180: * Execution Tokens Tutorial::   
  181: * Exceptions Tutorial::         
  182: * Defining Words Tutorial::     
  183: * Arrays and Records Tutorial::  
  184: * POSTPONE Tutorial::           
  185: * Literal Tutorial::            
  186: * Advanced macros Tutorial::    
  187: * Compilation Tokens Tutorial::  
  188: * Wordlists and Search Order Tutorial::  
  189: 
  190: An Introduction to ANS Forth
  191: 
  192: * Introducing the Text Interpreter::  
  193: * Stacks and Postfix notation::  
  194: * Your first definition::       
  195: * How does that work?::         
  196: * Forth is written in Forth::   
  197: * Review - elements of a Forth system::  
  198: * Where to go next::            
  199: * Exercises::                   
  200: 
  201: Forth Words
  202: 
  203: * Notation::                    
  204: * Case insensitivity::          
  205: * Comments::                    
  206: * Boolean Flags::               
  207: * Arithmetic::                  
  208: * Stack Manipulation::          
  209: * Memory::                      
  210: * Control Structures::          
  211: * Defining Words::              
  212: * Interpretation and Compilation Semantics::  
  213: * Tokens for Words::            
  214: * Compiling words::             
  215: * The Text Interpreter::        
  216: * The Input Stream::            
  217: * Word Lists::                  
  218: * Environmental Queries::       
  219: * Files::                       
  220: * Blocks::                      
  221: * Other I/O::                   
  222: * OS command line arguments::   
  223: * Locals::                      
  224: * Structures::                  
  225: * Object-oriented Forth::       
  226: * Programming Tools::           
  227: * C Interface::                 
  228: * Assembler and Code Words::    
  229: * Threading Words::             
  230: * Passing Commands to the OS::  
  231: * Keeping track of Time::       
  232: * Miscellaneous Words::         
  233: 
  234: Arithmetic
  235: 
  236: * Single precision::            
  237: * Double precision::            Double-cell integer arithmetic
  238: * Bitwise operations::          
  239: * Numeric comparison::          
  240: * Mixed precision::             Operations with single and double-cell integers
  241: * Floating Point::              
  242: 
  243: Stack Manipulation
  244: 
  245: * Data stack::                  
  246: * Floating point stack::        
  247: * Return stack::                
  248: * Locals stack::                
  249: * Stack pointer manipulation::  
  250: 
  251: Memory
  252: 
  253: * Memory model::                
  254: * Dictionary allocation::       
  255: * Heap Allocation::             
  256: * Memory Access::               
  257: * Address arithmetic::          
  258: * Memory Blocks::               
  259: 
  260: Control Structures
  261: 
  262: * Selection::                   IF ... ELSE ... ENDIF
  263: * Simple Loops::                BEGIN ...
  264: * Counted Loops::               DO
  265: * Arbitrary control structures::  
  266: * Calls and returns::           
  267: * Exception Handling::          
  268: 
  269: Defining Words
  270: 
  271: * CREATE::                      
  272: * Variables::                   Variables and user variables
  273: * Constants::                   
  274: * Values::                      Initialised variables
  275: * Colon Definitions::           
  276: * Anonymous Definitions::       Definitions without names
  277: * Quotations::                  
  278: * Supplying names::             Passing definition names as strings
  279: * User-defined Defining Words::  
  280: * Deferred Words::              Allow forward references
  281: * Aliases::                     
  282: 
  283: User-defined Defining Words
  284: 
  285: * CREATE..DOES> applications::  
  286: * CREATE..DOES> details::       
  287: * Advanced does> usage example::  
  288: * Const-does>::                 
  289: 
  290: Interpretation and Compilation Semantics
  291: 
  292: * Combined words::              
  293: 
  294: Tokens for Words
  295: 
  296: * Execution token::             represents execution/interpretation semantics
  297: * Compilation token::           represents compilation semantics
  298: * Name token::                  represents named words
  299: 
  300: Compiling words
  301: 
  302: * Literals::                    Compiling data values
  303: * Macros::                      Compiling words
  304: 
  305: The Text Interpreter
  306: 
  307: * Input Sources::               
  308: * Number Conversion::           
  309: * Interpret/Compile states::    
  310: * Interpreter Directives::      
  311: 
  312: Word Lists
  313: 
  314: * Vocabularies::                
  315: * Why use word lists?::         
  316: * Word list example::           
  317: 
  318: Files
  319: 
  320: * Forth source files::          
  321: * General files::               
  322: * Redirection::                 
  323: * Search Paths::                
  324: 
  325: Search Paths
  326: 
  327: * Source Search Paths::         
  328: * General Search Paths::        
  329: 
  330: Other I/O
  331: 
  332: * Simple numeric output::       Predefined formats
  333: * Formatted numeric output::    Formatted (pictured) output
  334: * String Formats::              How Forth stores strings in memory
  335: * Displaying characters and strings::  Other stuff
  336: * String words::                Gforth's little string library
  337: * Terminal output::             Cursor positioning etc.
  338: * Single-key input::            
  339: * Line input and conversion::   
  340: * Pipes::                       How to create your own pipes
  341: * Xchars and Unicode::          Non-ASCII characters
  342: 
  343: Locals
  344: 
  345: * Gforth locals::               
  346: * ANS Forth locals::            
  347: 
  348: Gforth locals
  349: 
  350: * Where are locals visible by name?::  
  351: * How long do locals live?::    
  352: * Locals programming style::    
  353: * Locals implementation::       
  354: 
  355: Structures
  356: 
  357: * Why explicit structure support?::  
  358: * Structure Usage::             
  359: * Structure Naming Convention::  
  360: * Structure Implementation::    
  361: * Structure Glossary::          
  362: * Forth200x Structures::        
  363: 
  364: Object-oriented Forth
  365: 
  366: * Why object-oriented programming?::  
  367: * Object-Oriented Terminology::  
  368: * Objects::                     
  369: * OOF::                         
  370: * Mini-OOF::                    
  371: * Comparison with other object models::  
  372: 
  373: The @file{objects.fs} model
  374: 
  375: * Properties of the Objects model::  
  376: * Basic Objects Usage::         
  377: * The Objects base class::      
  378: * Creating objects::            
  379: * Object-Oriented Programming Style::  
  380: * Class Binding::               
  381: * Method conveniences::         
  382: * Classes and Scoping::         
  383: * Dividing classes::            
  384: * Object Interfaces::           
  385: * Objects Implementation::      
  386: * Objects Glossary::            
  387: 
  388: The @file{oof.fs} model
  389: 
  390: * Properties of the OOF model::  
  391: * Basic OOF Usage::             
  392: * The OOF base class::          
  393: * Class Declaration::           
  394: * Class Implementation::        
  395: 
  396: The @file{mini-oof.fs} model
  397: 
  398: * Basic Mini-OOF Usage::        
  399: * Mini-OOF Example::            
  400: * Mini-OOF Implementation::     
  401: 
  402: Programming Tools
  403: 
  404: * Examining::                   Data and Code.
  405: * Forgetting words::            Usually before reloading.
  406: * Debugging::                   Simple and quick.
  407: * Assertions::                  Making your programs self-checking.
  408: * Singlestep Debugger::         Executing your program word by word.
  409: 
  410: C Interface
  411: 
  412: * Calling C Functions::         
  413: * Declaring C Functions::       
  414: * Calling C function pointers::  
  415: * Defining library interfaces::  
  416: * Declaring OS-level libraries::  
  417: * Callbacks::                   
  418: * C interface internals::       
  419: * Low-Level C Interface Words::  
  420: 
  421: Assembler and Code Words
  422: 
  423: * Assembler Definitions::       Definitions in assembly language
  424: * Common Assembler::            Assembler Syntax
  425: * Common Disassembler::         
  426: * 386 Assembler::               Deviations and special cases
  427: * AMD64 Assembler::             
  428: * Alpha Assembler::             Deviations and special cases
  429: * MIPS assembler::              Deviations and special cases
  430: * PowerPC assembler::           Deviations and special cases
  431: * ARM Assembler::               Deviations and special cases
  432: * Other assemblers::            How to write them
  433: 
  434: Tools
  435: 
  436: * ANS Report::                  Report the words used, sorted by wordset.
  437: * Stack depth changes::         Where does this stack item come from?
  438: 
  439: ANS conformance
  440: 
  441: * The Core Words::              
  442: * The optional Block word set::  
  443: * The optional Double Number word set::  
  444: * The optional Exception word set::  
  445: * The optional Facility word set::  
  446: * The optional File-Access word set::  
  447: * The optional Floating-Point word set::  
  448: * The optional Locals word set::  
  449: * The optional Memory-Allocation word set::  
  450: * The optional Programming-Tools word set::  
  451: * The optional Search-Order word set::  
  452: 
  453: The Core Words
  454: 
  455: * core-idef::                   Implementation Defined Options                   
  456: * core-ambcond::                Ambiguous Conditions                
  457: * core-other::                  Other System Documentation                  
  458: 
  459: The optional Block word set
  460: 
  461: * block-idef::                  Implementation Defined Options
  462: * block-ambcond::               Ambiguous Conditions               
  463: * block-other::                 Other System Documentation                 
  464: 
  465: The optional Double Number word set
  466: 
  467: * double-ambcond::              Ambiguous Conditions              
  468: 
  469: The optional Exception word set
  470: 
  471: * exception-idef::              Implementation Defined Options              
  472: 
  473: The optional Facility word set
  474: 
  475: * facility-idef::               Implementation Defined Options               
  476: * facility-ambcond::            Ambiguous Conditions            
  477: 
  478: The optional File-Access word set
  479: 
  480: * file-idef::                   Implementation Defined Options
  481: * file-ambcond::                Ambiguous Conditions                
  482: 
  483: The optional Floating-Point word set
  484: 
  485: * floating-idef::               Implementation Defined Options
  486: * floating-ambcond::            Ambiguous Conditions            
  487: 
  488: The optional Locals word set
  489: 
  490: * locals-idef::                 Implementation Defined Options                 
  491: * locals-ambcond::              Ambiguous Conditions              
  492: 
  493: The optional Memory-Allocation word set
  494: 
  495: * memory-idef::                 Implementation Defined Options                 
  496: 
  497: The optional Programming-Tools word set
  498: 
  499: * programming-idef::            Implementation Defined Options            
  500: * programming-ambcond::         Ambiguous Conditions         
  501: 
  502: The optional Search-Order word set
  503: 
  504: * search-idef::                 Implementation Defined Options                 
  505: * search-ambcond::              Ambiguous Conditions              
  506: 
  507: Emacs and Gforth
  508: 
  509: * Installing gforth.el::        Making Emacs aware of Forth.
  510: * Emacs Tags::                  Viewing the source of a word in Emacs.
  511: * Hilighting::                  Making Forth code look prettier.
  512: * Auto-Indentation::            Customizing auto-indentation.
  513: * Blocks Files::                Reading and writing blocks files.
  514: 
  515: Image Files
  516: 
  517: * Image Licensing Issues::      Distribution terms for images.
  518: * Image File Background::       Why have image files?
  519: * Non-Relocatable Image Files::  don't always work.
  520: * Data-Relocatable Image Files::  are better.
  521: * Fully Relocatable Image Files::  better yet.
  522: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
  523: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
  524: * Modifying the Startup Sequence::  and turnkey applications.
  525: 
  526: Fully Relocatable Image Files
  527: 
  528: * gforthmi::                    The normal way
  529: * cross.fs::                    The hard way
  530: 
  531: Engine
  532: 
  533: * Portability::                 
  534: * Threading::                   
  535: * Primitives::                  
  536: * Performance::                 
  537: 
  538: Threading
  539: 
  540: * Scheduling::                  
  541: * Direct or Indirect Threaded?::  
  542: * Dynamic Superinstructions::   
  543: * DOES>::                       
  544: 
  545: Primitives
  546: 
  547: * Automatic Generation::        
  548: * TOS Optimization::            
  549: * Produced code::               
  550: 
  551: Cross Compiler
  552: 
  553: * Using the Cross Compiler::    
  554: * How the Cross Compiler Works::  
  555: 
  556: Licenses
  557: 
  558: * GNU Free Documentation License::  License for copying this manual.
  559: * Copying::                     GPL (for copying this software).
  560: 
  561: @end detailmenu
  562: @end menu
  563: 
  564: @c ----------------------------------------------------------
  565: @iftex
  566: @unnumbered Preface
  567: @cindex Preface
  568: This manual documents Gforth. Some introductory material is provided for
  569: readers who are unfamiliar with Forth or who are migrating to Gforth
  570: from other Forth compilers. However, this manual is primarily a
  571: reference manual.
  572: @end iftex
  573: 
  574: @comment TODO much more blurb here.
  575: 
  576: @c ******************************************************************
  577: @node Goals, Gforth Environment, Top, Top
  578: @comment node-name,     next,           previous, up
  579: @chapter Goals of Gforth
  580: @cindex goals of the Gforth project
  581: The goal of the Gforth Project is to develop a standard model for
  582: ANS Forth. This can be split into several subgoals:
  583: 
  584: @itemize @bullet
  585: @item
  586: Gforth should conform to the ANS Forth Standard.
  587: @item
  588: It should be a model, i.e. it should define all the
  589: implementation-dependent things.
  590: @item
  591: It should become standard, i.e. widely accepted and used. This goal
  592: is the most difficult one.
  593: @end itemize
  594: 
  595: To achieve these goals Gforth should be
  596: @itemize @bullet
  597: @item
  598: Similar to previous models (fig-Forth, F83)
  599: @item
  600: Powerful. It should provide for all the things that are considered
  601: necessary today and even some that are not yet considered necessary.
  602: @item
  603: Efficient. It should not get the reputation of being exceptionally
  604: slow.
  605: @item
  606: Free.
  607: @item
  608: Available on many machines/easy to port.
  609: @end itemize
  610: 
  611: Have we achieved these goals? Gforth conforms to the ANS Forth
  612: standard. It may be considered a model, but we have not yet documented
  613: which parts of the model are stable and which parts we are likely to
  614: change. It certainly has not yet become a de facto standard, but it
  615: appears to be quite popular. It has some similarities to and some
  616: differences from previous models. It has some powerful features, but not
  617: yet everything that we envisioned. We certainly have achieved our
  618: execution speed goals (@pxref{Performance})@footnote{However, in 1998
  619: the bar was raised when the major commercial Forth vendors switched to
  620: native code compilers.}.  It is free and available on many machines.
  621: 
  622: @c ******************************************************************
  623: @node Gforth Environment, Tutorial, Goals, Top
  624: @chapter Gforth Environment
  625: @cindex Gforth environment
  626: 
  627: Note: ultimately, the Gforth man page will be auto-generated from the
  628: material in this chapter.
  629: 
  630: @menu
  631: * Invoking Gforth::             Getting in
  632: * Leaving Gforth::              Getting out
  633: * Command-line editing::        
  634: * Environment variables::       that affect how Gforth starts up
  635: * Gforth Files::                What gets installed and where
  636: * Gforth in pipes::             
  637: * Startup speed::               When 14ms is not fast enough ...
  638: @end menu
  639: 
  640: For related information about the creation of images see @ref{Image Files}.
  641: 
  642: @comment ----------------------------------------------
  643: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
  644: @section Invoking Gforth
  645: @cindex invoking Gforth
  646: @cindex running Gforth
  647: @cindex command-line options
  648: @cindex options on the command line
  649: @cindex flags on the command line
  650: 
  651: Gforth is made up of two parts; an executable ``engine'' (named
  652: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
  653: will usually just say @code{gforth} -- this automatically loads the
  654: default image file @file{gforth.fi}. In many other cases the default
  655: Gforth image will be invoked like this:
  656: @example
  657: gforth [file | -e forth-code] ...
  658: @end example
  659: @noindent
  660: This interprets the contents of the files and the Forth code in the order they
  661: are given.
  662: 
  663: In addition to the @command{gforth} engine, there is also an engine
  664: called @command{gforth-fast}, which is faster, but gives less
  665: informative error messages (@pxref{Error messages}) and may catch some
  666: errors (in particular, stack underflows and integer division errors)
  667: later or not at all.  You should use it for debugged,
  668: performance-critical programs.
  669: 
  670: Moreover, there is an engine called @command{gforth-itc}, which is
  671: useful in some backwards-compatibility situations (@pxref{Direct or
  672: Indirect Threaded?}).
  673: 
  674: In general, the command line looks like this:
  675: 
  676: @example
  677: gforth[-fast] [engine options] [image options]
  678: @end example
  679: 
  680: The engine options must come before the rest of the command
  681: line. They are:
  682: 
  683: @table @code
  684: @cindex -i, command-line option
  685: @cindex --image-file, command-line option
  686: @item --image-file @i{file}
  687: @itemx -i @i{file}
  688: Loads the Forth image @i{file} instead of the default
  689: @file{gforth.fi} (@pxref{Image Files}).
  690: 
  691: @cindex --appl-image, command-line option
  692: @item --appl-image @i{file}
  693: Loads the image @i{file} and leaves all further command-line arguments
  694: to the image (instead of processing them as engine options).  This is
  695: useful for building executable application images on Unix, built with
  696: @code{gforthmi --application ...}.
  697: 
  698: @cindex --path, command-line option
  699: @cindex -p, command-line option
  700: @item --path @i{path}
  701: @itemx -p @i{path}
  702: Uses @i{path} for searching the image file and Forth source code files
  703: instead of the default in the environment variable @code{GFORTHPATH} or
  704: the path specified at installation time (e.g.,
  705: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
  706: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
  707: 
  708: @cindex --dictionary-size, command-line option
  709: @cindex -m, command-line option
  710: @cindex @i{size} parameters for command-line options
  711: @cindex size of the dictionary and the stacks
  712: @item --dictionary-size @i{size}
  713: @itemx -m @i{size}
  714: Allocate @i{size} space for the Forth dictionary space instead of
  715: using the default specified in the image (typically 256K). The
  716: @i{size} specification for this and subsequent options consists of
  717: an integer and a unit (e.g.,
  718: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
  719: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
  720: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
  721: @code{e} is used.
  722: 
  723: @cindex --data-stack-size, command-line option
  724: @cindex -d, command-line option
  725: @item --data-stack-size @i{size}
  726: @itemx -d @i{size}
  727: Allocate @i{size} space for the data stack instead of using the
  728: default specified in the image (typically 16K).
  729: 
  730: @cindex --return-stack-size, command-line option
  731: @cindex -r, command-line option
  732: @item --return-stack-size @i{size}
  733: @itemx -r @i{size}
  734: Allocate @i{size} space for the return stack instead of using the
  735: default specified in the image (typically 15K).
  736: 
  737: @cindex --fp-stack-size, command-line option
  738: @cindex -f, command-line option
  739: @item --fp-stack-size @i{size}
  740: @itemx -f @i{size}
  741: Allocate @i{size} space for the floating point stack instead of
  742: using the default specified in the image (typically 15.5K). In this case
  743: the unit specifier @code{e} refers to floating point numbers.
  744: 
  745: @cindex --locals-stack-size, command-line option
  746: @cindex -l, command-line option
  747: @item --locals-stack-size @i{size}
  748: @itemx -l @i{size}
  749: Allocate @i{size} space for the locals stack instead of using the
  750: default specified in the image (typically 14.5K).
  751: 
  752: @cindex --vm-commit, command-line option
  753: @cindex overcommit memory for dictionary and stacks
  754: @cindex memory overcommit for dictionary and stacks
  755: @item --vm-commit
  756: Normally, Gforth tries to start up even if there is not enough virtual
  757: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
  758: on OSs that support it); so you can ask for a really big dictionary
  759: and/or stacks, and as long as you don't use more virtual memory than
  760: is available, everything will be fine (but if you use more, processes
  761: get killed).  With this option you just use the default allocation
  762: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
  763: means that you cannot and should not ask for as big dictionary and
  764: stacks, but once Gforth successfully starts up, out-of-memory won't
  765: kill it.
  766: 
  767: @cindex -h, command-line option
  768: @cindex --help, command-line option
  769: @item --help
  770: @itemx -h
  771: Print a message about the command-line options
  772: 
  773: @cindex -v, command-line option
  774: @cindex --version, command-line option
  775: @item --version
  776: @itemx -v
  777: Print version and exit
  778: 
  779: @cindex --debug, command-line option
  780: @item --debug
  781: Print some information useful for debugging on startup.
  782: 
  783: @cindex --offset-image, command-line option
  784: @item --offset-image
  785: Start the dictionary at a slightly different position than would be used
  786: otherwise (useful for creating data-relocatable images,
  787: @pxref{Data-Relocatable Image Files}).
  788: 
  789: @cindex --no-offset-im, command-line option
  790: @item --no-offset-im
  791: Start the dictionary at the normal position.
  792: 
  793: @cindex --clear-dictionary, command-line option
  794: @item --clear-dictionary
  795: Initialize all bytes in the dictionary to 0 before loading the image
  796: (@pxref{Data-Relocatable Image Files}).
  797: 
  798: @cindex --die-on-signal, command-line-option
  799: @item --die-on-signal
  800: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
  801: or the segmentation violation SIGSEGV) by translating it into a Forth
  802: @code{THROW}. With this option, Gforth exits if it receives such a
  803: signal. This option is useful when the engine and/or the image might be
  804: severely broken (such that it causes another signal before recovering
  805: from the first); this option avoids endless loops in such cases.
  806: 
  807: @cindex --no-dynamic, command-line option
  808: @cindex --dynamic, command-line option
  809: @item --no-dynamic
  810: @item --dynamic
  811: Disable or enable dynamic superinstructions with replication
  812: (@pxref{Dynamic Superinstructions}).
  813: 
  814: @cindex --no-super, command-line option
  815: @item --no-super
  816: Disable dynamic superinstructions, use just dynamic replication; this is
  817: useful if you want to patch threaded code (@pxref{Dynamic
  818: Superinstructions}).
  819: 
  820: @cindex --ss-number, command-line option
  821: @item --ss-number=@var{N}
  822: Use only the first @var{N} static superinstructions compiled into the
  823: engine (default: use them all; note that only @code{gforth-fast} has
  824: any).  This option is useful for measuring the performance impact of
  825: static superinstructions.
  826: 
  827: @cindex --ss-min-..., command-line options
  828: @item --ss-min-codesize
  829: @item --ss-min-ls
  830: @item --ss-min-lsu
  831: @item --ss-min-nexts
  832: Use specified metric for determining the cost of a primitive or static
  833: superinstruction for static superinstruction selection.  @code{Codesize}
  834: is the native code size of the primive or static superinstruction,
  835: @code{ls} is the number of loads and stores, @code{lsu} is the number of
  836: loads, stores, and updates, and @code{nexts} is the number of dispatches
  837: (not taking dynamic superinstructions into account), i.e. every
  838: primitive or static superinstruction has cost 1. Default:
  839: @code{codesize} if you use dynamic code generation, otherwise
  840: @code{nexts}.
  841: 
  842: @cindex --ss-greedy, command-line option
  843: @item --ss-greedy
  844: This option is useful for measuring the performance impact of static
  845: superinstructions.  By default, an optimal shortest-path algorithm is
  846: used for selecting static superinstructions.  With @option{--ss-greedy}
  847: this algorithm is modified to assume that anything after the static
  848: superinstruction currently under consideration is not combined into
  849: static superinstructions.  With @option{--ss-min-nexts} this produces
  850: the same result as a greedy algorithm that always selects the longest
  851: superinstruction available at the moment.  E.g., if there are
  852: superinstructions AB and BCD, then for the sequence A B C D the optimal
  853: algorithm will select A BCD and the greedy algorithm will select AB C D.
  854: 
  855: @cindex --print-metrics, command-line option
  856: @item --print-metrics
  857: Prints some metrics used during static superinstruction selection:
  858: @code{code size} is the actual size of the dynamically generated code.
  859: @code{Metric codesize} is the sum of the codesize metrics as seen by
  860: static superinstruction selection; there is a difference from @code{code
  861: size}, because not all primitives and static superinstructions are
  862: compiled into dynamically generated code, and because of markers.  The
  863: other metrics correspond to the @option{ss-min-...} options.  This
  864: option is useful for evaluating the effects of the @option{--ss-...}
  865: options.
  866: 
  867: @end table
  868: 
  869: @cindex loading files at startup
  870: @cindex executing code on startup
  871: @cindex batch processing with Gforth
  872: As explained above, the image-specific command-line arguments for the
  873: default image @file{gforth.fi} consist of a sequence of filenames and
  874: @code{-e @var{forth-code}} options that are interpreted in the sequence
  875: in which they are given. The @code{-e @var{forth-code}} or
  876: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
  877: option takes only one argument; if you want to evaluate more Forth
  878: words, you have to quote them or use @code{-e} several times. To exit
  879: after processing the command line (instead of entering interactive mode)
  880: append @code{-e bye} to the command line.  You can also process the
  881: command-line arguments with a Forth program (@pxref{OS command line
  882: arguments}).
  883: 
  884: @cindex versions, invoking other versions of Gforth
  885: If you have several versions of Gforth installed, @code{gforth} will
  886: invoke the version that was installed last. @code{gforth-@i{version}}
  887: invokes a specific version. If your environment contains the variable
  888: @code{GFORTHPATH}, you may want to override it by using the
  889: @code{--path} option.
  890: 
  891: Not yet implemented:
  892: On startup the system first executes the system initialization file
  893: (unless the option @code{--no-init-file} is given; note that the system
  894: resulting from using this option may not be ANS Forth conformant). Then
  895: the user initialization file @file{.gforth.fs} is executed, unless the
  896: option @code{--no-rc} is given; this file is searched for in @file{.},
  897: then in @file{~}, then in the normal path (see above).
  898: 
  899: 
  900: 
  901: @comment ----------------------------------------------
  902: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
  903: @section Leaving Gforth
  904: @cindex Gforth - leaving
  905: @cindex leaving Gforth
  906: 
  907: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
  908: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
  909: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
  910: data are discarded.  For ways of saving the state of the system before
  911: leaving Gforth see @ref{Image Files}.
  912: 
  913: doc-bye
  914: 
  915: 
  916: @comment ----------------------------------------------
  917: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
  918: @section Command-line editing
  919: @cindex command-line editing
  920: 
  921: Gforth maintains a history file that records every line that you type to
  922: the text interpreter. This file is preserved between sessions, and is
  923: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
  924: repeatedly you can recall successively older commands from this (or
  925: previous) session(s). The full list of command-line editing facilities is:
  926: 
  927: @itemize @bullet
  928: @item
  929: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
  930: commands from the history buffer.
  931: @item
  932: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
  933: from the history buffer.
  934: @item
  935: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
  936: @item
  937: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
  938: @item
  939: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
  940: closing up the line.
  941: @item
  942: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
  943: @item
  944: @kbd{Ctrl-a} to move the cursor to the start of the line.
  945: @item
  946: @kbd{Ctrl-e} to move the cursor to the end of the line.
  947: @item
  948: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
  949: line.
  950: @item
  951: @key{TAB} to step through all possible full-word completions of the word
  952: currently being typed.
  953: @item
  954: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
  955: using @code{bye}). 
  956: @item
  957: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
  958: character under the cursor.
  959: @end itemize
  960: 
  961: When editing, displayable characters are inserted to the left of the
  962: cursor position; the line is always in ``insert'' (as opposed to
  963: ``overstrike'') mode.
  964: 
  965: @cindex history file
  966: @cindex @file{.gforth-history}
  967: On Unix systems, the history file is @file{~/.gforth-history} by
  968: default@footnote{i.e. it is stored in the user's home directory.}. You
  969: can find out the name and location of your history file using:
  970: 
  971: @example 
  972: history-file type \ Unix-class systems
  973: 
  974: history-file type \ Other systems
  975: history-dir  type
  976: @end example
  977: 
  978: If you enter long definitions by hand, you can use a text editor to
  979: paste them out of the history file into a Forth source file for reuse at
  980: a later time.
  981: 
  982: Gforth never trims the size of the history file, so you should do this
  983: periodically, if necessary.
  984: 
  985: @comment this is all defined in history.fs
  986: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
  987: @comment chosen?
  988: 
  989: 
  990: @comment ----------------------------------------------
  991: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
  992: @section Environment variables
  993: @cindex environment variables
  994: 
  995: Gforth uses these environment variables:
  996: 
  997: @itemize @bullet
  998: @item
  999: @cindex @code{GFORTHHIST} -- environment variable
 1000: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
 1001: open/create the history file, @file{.gforth-history}. Default:
 1002: @code{$HOME}.
 1003: 
 1004: @item
 1005: @cindex @code{GFORTHPATH} -- environment variable
 1006: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
 1007: for Forth source-code files.
 1008: 
 1009: @item
 1010: @cindex @code{LANG} -- environment variable
 1011: @code{LANG} -- see @code{LC_CTYPE}
 1012: 
 1013: @item
 1014: @cindex @code{LC_ALL} -- environment variable
 1015: @code{LC_ALL} -- see @code{LC_CTYPE}
 1016: 
 1017: @item
 1018: @cindex @code{LC_CTYPE} -- environment variable
 1019: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
 1020: startup, Gforth uses the UTF-8 encoding for strings internally and
 1021: expects its input and produces its output in UTF-8 encoding, otherwise
 1022: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
 1023: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
 1024: that is unset, in @code{LANG}.
 1025: 
 1026: @item
 1027: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
 1028: 
 1029: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
 1030: of @code{system} before passing it to C's @code{system()}.  Default:
 1031: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
 1032: and the command are directly concatenated, so if a space between them is
 1033: necessary, append it to the prefix.
 1034: 
 1035: @item
 1036: @cindex @code{GFORTH} -- environment variable
 1037: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
 1038: 
 1039: @item
 1040: @cindex @code{GFORTHD} -- environment variable
 1041: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
 1042: 
 1043: @item
 1044: @cindex @code{TMP}, @code{TEMP} - environment variable
 1045: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
 1046: location for the history file.
 1047: @end itemize
 1048: 
 1049: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
 1050: @comment mentioning these.
 1051: 
 1052: All the Gforth environment variables default to sensible values if they
 1053: are not set.
 1054: 
 1055: 
 1056: @comment ----------------------------------------------
 1057: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
 1058: @section Gforth files
 1059: @cindex Gforth files
 1060: 
 1061: When you install Gforth on a Unix system, it installs files in these
 1062: locations by default:
 1063: 
 1064: @itemize @bullet
 1065: @item
 1066: @file{/usr/local/bin/gforth}
 1067: @item
 1068: @file{/usr/local/bin/gforthmi}
 1069: @item
 1070: @file{/usr/local/man/man1/gforth.1} - man page.
 1071: @item
 1072: @file{/usr/local/info} - the Info version of this manual.
 1073: @item
 1074: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
 1075: @item
 1076: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
 1077: @item
 1078: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
 1079: @item
 1080: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
 1081: @end itemize
 1082: 
 1083: You can select different places for installation by using
 1084: @code{configure} options (listed with @code{configure --help}).
 1085: 
 1086: @comment ----------------------------------------------
 1087: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
 1088: @section Gforth in pipes
 1089: @cindex pipes, Gforth as part of
 1090: 
 1091: Gforth can be used in pipes created elsewhere (described here).  It can
 1092: also create pipes on its own (@pxref{Pipes}).
 1093: 
 1094: @cindex input from pipes
 1095: If you pipe into Gforth, your program should read with @code{read-file}
 1096: or @code{read-line} from @code{stdin} (@pxref{General files}).
 1097: @code{Key} does not recognize the end of input.  Words like
 1098: @code{accept} echo the input and are therefore usually not useful for
 1099: reading from a pipe.  You have to invoke the Forth program with an OS
 1100: command-line option, as you have no chance to use the Forth command line
 1101: (the text interpreter would try to interpret the pipe input).
 1102: 
 1103: @cindex output in pipes
 1104: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
 1105: 
 1106: @cindex silent exiting from Gforth
 1107: When you write to a pipe that has been closed at the other end, Gforth
 1108: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
 1109: into the exception @code{broken-pipe-error}.  If your application does
 1110: not catch that exception, the system catches it and exits, usually
 1111: silently (unless you were working on the Forth command line; then it
 1112: prints an error message and exits).  This is usually the desired
 1113: behaviour.
 1114: 
 1115: If you do not like this behaviour, you have to catch the exception
 1116: yourself, and react to it.
 1117: 
 1118: Here's an example of an invocation of Gforth that is usable in a pipe:
 1119: 
 1120: @example
 1121: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
 1122:  type repeat ; foo bye"
 1123: @end example
 1124: 
 1125: This example just copies the input verbatim to the output.  A very
 1126: simple pipe containing this example looks like this:
 1127: 
 1128: @example
 1129: cat startup.fs |
 1130: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
 1131:  type repeat ; foo bye"|
 1132: head
 1133: @end example
 1134: 
 1135: @cindex stderr and pipes
 1136: Pipes involving Gforth's @code{stderr} output do not work.
 1137: 
 1138: @comment ----------------------------------------------
 1139: @node Startup speed,  , Gforth in pipes, Gforth Environment
 1140: @section Startup speed
 1141: @cindex Startup speed
 1142: @cindex speed, startup
 1143: 
 1144: If Gforth is used for CGI scripts or in shell scripts, its startup
 1145: speed may become a problem.  On a 3GHz Core 2 Duo E8400 under 64-bit
 1146: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
 1147: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
 1148: with about 3.4ms user time and 1.2ms system time, because it subsumes
 1149: some of the options discussed below).
 1150: 
 1151: If startup speed is a problem, you may consider the following ways to
 1152: improve it; or you may consider ways to reduce the number of startups
 1153: (for example, by using Fast-CGI).  Note that the first steps below
 1154: improve the startup time at the cost of run-time (including
 1155: compile-time), so whether they are profitable depends on the balance
 1156: of these times in your application.
 1157: 
 1158: An easy step that influences Gforth startup speed is the use of a
 1159: number of options that increase run-time, but decrease image-loading
 1160: time.
 1161: 
 1162: The first of these that you should try is @code{--ss-number=0
 1163: --ss-states=1} because this option buys relatively little run-time
 1164: speedup and costs quite a bit of time at startup.  @code{gforth-fast
 1165: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
 1166: system time.
 1167: 
 1168: The next option is @code{--no-dynamic} which has a substantial impact
 1169: on run-time (about a factor of 2 on several platforms), but still
 1170: makes startup speed a little faster: @code{gforth-fast --ss-number=0
 1171: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
 1172: system time.
 1173: 
 1174: The next step to improve startup speed is to use a data-relocatable
 1175: image (@pxref{Data-Relocatable Image Files}).  This avoids the
 1176: relocation cost for the code in the image (but not for the data).
 1177: Note that the image is then specific to the particular binary you are
 1178: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
 1179: the particular build).  You create the data-relocatable image that
 1180: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
 1181: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
 1182: required here or the image will not work).  And you run it with
 1183: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
 1184: above don't matter here, because they only come into play on
 1185: relocatable code).  @code{gforth-fast -i gforthdr.fi -e bye} takes
 1186: about 1.1ms user and 1.2ms system time.
 1187: 
 1188: One step further is to avoid all relocation cost and part of the
 1189: copy-on-write cost through using a non-relocatable image
 1190: (@pxref{Non-Relocatable Image Files}).  However, this has the
 1191: disadvantage that it does not work on operating systems with address
 1192: space randomization (the default in, e.g., Linux nowadays), or if the
 1193: dictionary moves for any other reason (e.g., because of a change of
 1194: the OS kernel or an updated library), so we cannot really recommend
 1195: it.  You create a non-relocatable image with @code{gforth-fast
 1196: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
 1197: is required here, too).  And you run it with @code{gforth-fast -i
 1198: gforthnr.fi ... -e bye} (again the flags discussed above don't
 1199: matter).  @code{gforth-fast -i gforthdr.fi -e bye} takes
 1200: about 0.9ms user and 0.9ms system time.
 1201: 
 1202: If the script you want to execute contains a significant amount of
 1203: code, it may be profitable to compile it into the image to avoid the
 1204: cost of compiling it at startup time.
 1205: 
 1206: @c ******************************************************************
 1207: @node Tutorial, Introduction, Gforth Environment, Top
 1208: @chapter Forth Tutorial
 1209: @cindex Tutorial
 1210: @cindex Forth Tutorial
 1211: 
 1212: @c Topics from nac's Introduction that could be mentioned:
 1213: @c press <ret> after each line
 1214: @c Prompt
 1215: @c numbers vs. words in dictionary on text interpretation
 1216: @c what happens on redefinition
 1217: @c parsing words (in particular, defining words)
 1218: 
 1219: The difference of this chapter from the Introduction
 1220: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
 1221: be used while sitting in front of a computer, and covers much more
 1222: material, but does not explain how the Forth system works.
 1223: 
 1224: This tutorial can be used with any ANS-compliant Forth; any
 1225: Gforth-specific features are marked as such and you can skip them if
 1226: you work with another Forth.  This tutorial does not explain all
 1227: features of Forth, just enough to get you started and give you some
 1228: ideas about the facilities available in Forth.  Read the rest of the
 1229: manual when you are through this.
 1230: 
 1231: The intended way to use this tutorial is that you work through it while
 1232: sitting in front of the console, take a look at the examples and predict
 1233: what they will do, then try them out; if the outcome is not as expected,
 1234: find out why (e.g., by trying out variations of the example), so you
 1235: understand what's going on.  There are also some assignments that you
 1236: should solve.
 1237: 
 1238: This tutorial assumes that you have programmed before and know what,
 1239: e.g., a loop is.
 1240: 
 1241: @c !! explain compat library
 1242: 
 1243: @menu
 1244: * Starting Gforth Tutorial::    
 1245: * Syntax Tutorial::             
 1246: * Crash Course Tutorial::       
 1247: * Stack Tutorial::              
 1248: * Arithmetics Tutorial::        
 1249: * Stack Manipulation Tutorial::  
 1250: * Using files for Forth code Tutorial::  
 1251: * Comments Tutorial::           
 1252: * Colon Definitions Tutorial::  
 1253: * Decompilation Tutorial::      
 1254: * Stack-Effect Comments Tutorial::  
 1255: * Types Tutorial::              
 1256: * Factoring Tutorial::          
 1257: * Designing the stack effect Tutorial::  
 1258: * Local Variables Tutorial::    
 1259: * Conditional execution Tutorial::  
 1260: * Flags and Comparisons Tutorial::  
 1261: * General Loops Tutorial::      
 1262: * Counted loops Tutorial::      
 1263: * Recursion Tutorial::          
 1264: * Leaving definitions or loops Tutorial::  
 1265: * Return Stack Tutorial::       
 1266: * Memory Tutorial::             
 1267: * Characters and Strings Tutorial::  
 1268: * Alignment Tutorial::          
 1269: * Floating Point Tutorial::     
 1270: * Files Tutorial::              
 1271: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
 1272: * Execution Tokens Tutorial::   
 1273: * Exceptions Tutorial::         
 1274: * Defining Words Tutorial::     
 1275: * Arrays and Records Tutorial::  
 1276: * POSTPONE Tutorial::           
 1277: * Literal Tutorial::            
 1278: * Advanced macros Tutorial::    
 1279: * Compilation Tokens Tutorial::  
 1280: * Wordlists and Search Order Tutorial::  
 1281: @end menu
 1282: 
 1283: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
 1284: @section Starting Gforth
 1285: @cindex starting Gforth tutorial
 1286: You can start Gforth by typing its name:
 1287: 
 1288: @example
 1289: gforth
 1290: @end example
 1291: 
 1292: That puts you into interactive mode; you can leave Gforth by typing
 1293: @code{bye}.  While in Gforth, you can edit the command line and access
 1294: the command line history with cursor keys, similar to bash.
 1295: 
 1296: 
 1297: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
 1298: @section Syntax
 1299: @cindex syntax tutorial
 1300: 
 1301: A @dfn{word} is a sequence of arbitrary characters (except white
 1302: space).  Words are separated by white space.  E.g., each of the
 1303: following lines contains exactly one word:
 1304: 
 1305: @example
 1306: word
 1307: !@@#$%^&*()
 1308: 1234567890
 1309: 5!a
 1310: @end example
 1311: 
 1312: A frequent beginner's error is to leave out necessary white space,
 1313: resulting in an error like @samp{Undefined word}; so if you see such an
 1314: error, check if you have put spaces wherever necessary.
 1315: 
 1316: @example
 1317: ." hello, world" \ correct
 1318: ."hello, world"  \ gives an "Undefined word" error
 1319: @end example
 1320: 
 1321: Gforth and most other Forth systems ignore differences in case (they are
 1322: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
 1323: your system is case-sensitive, you may have to type all the examples
 1324: given here in upper case.
 1325: 
 1326: 
 1327: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
 1328: @section Crash Course
 1329: 
 1330: Forth does not prevent you from shooting yourself in the foot.  Let's
 1331: try a few ways to crash Gforth:
 1332: 
 1333: @example
 1334: 0 0 !
 1335: here execute
 1336: ' catch >body 20 erase abort
 1337: ' (quit) >body 20 erase
 1338: @end example
 1339: 
 1340: The last two examples are guaranteed to destroy important parts of
 1341: Gforth (and most other systems), so you better leave Gforth afterwards
 1342: (if it has not finished by itself).  On some systems you may have to
 1343: kill gforth from outside (e.g., in Unix with @code{kill}).
 1344: 
 1345: You will find out later what these lines do and then you will get an
 1346: idea why they produce crashes.
 1347: 
 1348: Now that you know how to produce crashes (and that there's not much to
 1349: them), let's learn how to produce meaningful programs.
 1350: 
 1351: 
 1352: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
 1353: @section Stack
 1354: @cindex stack tutorial
 1355: 
 1356: The most obvious feature of Forth is the stack.  When you type in a
 1357: number, it is pushed on the stack.  You can display the contents of the
 1358: stack with @code{.s}.
 1359: 
 1360: @example
 1361: 1 2 .s
 1362: 3 .s
 1363: @end example
 1364: 
 1365: @code{.s} displays the top-of-stack to the right, i.e., the numbers
 1366: appear in @code{.s} output as they appeared in the input.
 1367: 
 1368: You can print the top element of the stack with @code{.}.
 1369: 
 1370: @example
 1371: 1 2 3 . . .
 1372: @end example
 1373: 
 1374: In general, words consume their stack arguments (@code{.s} is an
 1375: exception).
 1376: 
 1377: @quotation Assignment
 1378: What does the stack contain after @code{5 6 7 .}?
 1379: @end quotation
 1380: 
 1381: 
 1382: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
 1383: @section Arithmetics
 1384: @cindex arithmetics tutorial
 1385: 
 1386: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
 1387: operate on the top two stack items:
 1388: 
 1389: @example
 1390: 2 2 .s
 1391: + .s
 1392: .
 1393: 2 1 - .
 1394: 7 3 mod .
 1395: @end example
 1396: 
 1397: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
 1398: as in the corresponding infix expression (this is generally the case in
 1399: Forth).
 1400: 
 1401: Parentheses are superfluous (and not available), because the order of
 1402: the words unambiguously determines the order of evaluation and the
 1403: operands:
 1404: 
 1405: @example
 1406: 3 4 + 5 * .
 1407: 3 4 5 * + .
 1408: @end example
 1409: 
 1410: @quotation Assignment
 1411: What are the infix expressions corresponding to the Forth code above?
 1412: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
 1413: known as Postfix or RPN (Reverse Polish Notation).}.
 1414: @end quotation
 1415: 
 1416: To change the sign, use @code{negate}:
 1417: 
 1418: @example
 1419: 2 negate .
 1420: @end example
 1421: 
 1422: @quotation Assignment
 1423: Convert -(-3)*4-5 to Forth.
 1424: @end quotation
 1425: 
 1426: @code{/mod} performs both @code{/} and @code{mod}.
 1427: 
 1428: @example
 1429: 7 3 /mod . .
 1430: @end example
 1431: 
 1432: Reference: @ref{Arithmetic}.
 1433: 
 1434: 
 1435: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
 1436: @section Stack Manipulation
 1437: @cindex stack manipulation tutorial
 1438: 
 1439: Stack manipulation words rearrange the data on the stack.
 1440: 
 1441: @example
 1442: 1 .s drop .s
 1443: 1 .s dup .s drop drop .s
 1444: 1 2 .s over .s drop drop drop
 1445: 1 2 .s swap .s drop drop
 1446: 1 2 3 .s rot .s drop drop drop
 1447: @end example
 1448: 
 1449: These are the most important stack manipulation words.  There are also
 1450: variants that manipulate twice as many stack items:
 1451: 
 1452: @example
 1453: 1 2 3 4 .s 2swap .s 2drop 2drop
 1454: @end example
 1455: 
 1456: Two more stack manipulation words are:
 1457: 
 1458: @example
 1459: 1 2 .s nip .s drop
 1460: 1 2 .s tuck .s 2drop drop
 1461: @end example
 1462: 
 1463: @quotation Assignment
 1464: Replace @code{nip} and @code{tuck} with combinations of other stack
 1465: manipulation words.
 1466: 
 1467: @example
 1468: Given:          How do you get:
 1469: 1 2 3           3 2 1           
 1470: 1 2 3           1 2 3 2                 
 1471: 1 2 3           1 2 3 3                 
 1472: 1 2 3           1 3 3           
 1473: 1 2 3           2 1 3           
 1474: 1 2 3 4         4 3 2 1         
 1475: 1 2 3           1 2 3 1 2 3             
 1476: 1 2 3 4         1 2 3 4 1 2             
 1477: 1 2 3
 1478: 1 2 3           1 2 3 4                 
 1479: 1 2 3           1 3             
 1480: @end example
 1481: @end quotation
 1482: 
 1483: @example
 1484: 5 dup * .
 1485: @end example
 1486: 
 1487: @quotation Assignment
 1488: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
 1489: Write a piece of Forth code that expects two numbers on the stack
 1490: (@var{a} and @var{b}, with @var{b} on top) and computes
 1491: @code{(a-b)(a+1)}.
 1492: @end quotation
 1493: 
 1494: Reference: @ref{Stack Manipulation}.
 1495: 
 1496: 
 1497: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
 1498: @section Using files for Forth code
 1499: @cindex loading Forth code, tutorial
 1500: @cindex files containing Forth code, tutorial
 1501: 
 1502: While working at the Forth command line is convenient for one-line
 1503: examples and short one-off code, you probably want to store your source
 1504: code in files for convenient editing and persistence.  You can use your
 1505: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
 1506: Gforth}) to create @var{file.fs} and use
 1507: 
 1508: @example
 1509: s" @var{file.fs}" included
 1510: @end example
 1511: 
 1512: to load it into your Forth system.  The file name extension I use for
 1513: Forth files is @samp{.fs}.
 1514: 
 1515: You can easily start Gforth with some files loaded like this:
 1516: 
 1517: @example
 1518: gforth @var{file1.fs} @var{file2.fs}
 1519: @end example
 1520: 
 1521: If an error occurs during loading these files, Gforth terminates,
 1522: whereas an error during @code{INCLUDED} within Gforth usually gives you
 1523: a Gforth command line.  Starting the Forth system every time gives you a
 1524: clean start every time, without interference from the results of earlier
 1525: tries.
 1526: 
 1527: I often put all the tests in a file, then load the code and run the
 1528: tests with
 1529: 
 1530: @example
 1531: gforth @var{code.fs} @var{tests.fs} -e bye
 1532: @end example
 1533: 
 1534: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
 1535: @code{-e bye} ensures that Gforth terminates afterwards so that I can
 1536: restart this command without ado.
 1537: 
 1538: The advantage of this approach is that the tests can be repeated easily
 1539: every time the program ist changed, making it easy to catch bugs
 1540: introduced by the change.
 1541: 
 1542: Reference: @ref{Forth source files}.
 1543: 
 1544: 
 1545: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
 1546: @section Comments
 1547: @cindex comments tutorial
 1548: 
 1549: @example
 1550: \ That's a comment; it ends at the end of the line
 1551: ( Another comment; it ends here: )  .s
 1552: @end example
 1553: 
 1554: @code{\} and @code{(} are ordinary Forth words and therefore have to be
 1555: separated with white space from the following text.
 1556: 
 1557: @example
 1558: \This gives an "Undefined word" error
 1559: @end example
 1560: 
 1561: The first @code{)} ends a comment started with @code{(}, so you cannot
 1562: nest @code{(}-comments; and you cannot comment out text containing a
 1563: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
 1564: avoid @code{)} in word names.}.
 1565: 
 1566: I use @code{\}-comments for descriptive text and for commenting out code
 1567: of one or more line; I use @code{(}-comments for describing the stack
 1568: effect, the stack contents, or for commenting out sub-line pieces of
 1569: code.
 1570: 
 1571: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
 1572: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
 1573: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
 1574: with @kbd{M-q}.
 1575: 
 1576: Reference: @ref{Comments}.
 1577: 
 1578: 
 1579: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
 1580: @section Colon Definitions
 1581: @cindex colon definitions, tutorial
 1582: @cindex definitions, tutorial
 1583: @cindex procedures, tutorial
 1584: @cindex functions, tutorial
 1585: 
 1586: are similar to procedures and functions in other programming languages.
 1587: 
 1588: @example
 1589: : squared ( n -- n^2 )
 1590:    dup * ;
 1591: 5 squared .
 1592: 7 squared .
 1593: @end example
 1594: 
 1595: @code{:} starts the colon definition; its name is @code{squared}.  The
 1596: following comment describes its stack effect.  The words @code{dup *}
 1597: are not executed, but compiled into the definition.  @code{;} ends the
 1598: colon definition.
 1599: 
 1600: The newly-defined word can be used like any other word, including using
 1601: it in other definitions:
 1602: 
 1603: @example
 1604: : cubed ( n -- n^3 )
 1605:    dup squared * ;
 1606: -5 cubed .
 1607: : fourth-power ( n -- n^4 )
 1608:    squared squared ;
 1609: 3 fourth-power .
 1610: @end example
 1611: 
 1612: @quotation Assignment
 1613: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
 1614: @code{/mod} in terms of other Forth words, and check if they work (hint:
 1615: test your tests on the originals first).  Don't let the
 1616: @samp{redefined}-Messages spook you, they are just warnings.
 1617: @end quotation
 1618: 
 1619: Reference: @ref{Colon Definitions}.
 1620: 
 1621: 
 1622: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
 1623: @section Decompilation
 1624: @cindex decompilation tutorial
 1625: @cindex see tutorial
 1626: 
 1627: You can decompile colon definitions with @code{see}:
 1628: 
 1629: @example
 1630: see squared
 1631: see cubed
 1632: @end example
 1633: 
 1634: In Gforth @code{see} shows you a reconstruction of the source code from
 1635: the executable code.  Informations that were present in the source, but
 1636: not in the executable code, are lost (e.g., comments).
 1637: 
 1638: You can also decompile the predefined words:
 1639: 
 1640: @example
 1641: see .
 1642: see +
 1643: @end example
 1644: 
 1645: 
 1646: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
 1647: @section Stack-Effect Comments
 1648: @cindex stack-effect comments, tutorial
 1649: @cindex --, tutorial
 1650: By convention the comment after the name of a definition describes the
 1651: stack effect: The part in front of the @samp{--} describes the state of
 1652: the stack before the execution of the definition, i.e., the parameters
 1653: that are passed into the colon definition; the part behind the @samp{--}
 1654: is the state of the stack after the execution of the definition, i.e.,
 1655: the results of the definition.  The stack comment only shows the top
 1656: stack items that the definition accesses and/or changes.
 1657: 
 1658: You should put a correct stack effect on every definition, even if it is
 1659: just @code{( -- )}.  You should also add some descriptive comment to
 1660: more complicated words (I usually do this in the lines following
 1661: @code{:}).  If you don't do this, your code becomes unreadable (because
 1662: you have to work through every definition before you can understand
 1663: any).
 1664: 
 1665: @quotation Assignment
 1666: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
 1667: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
 1668: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
 1669: are done, you can compare your stack effects to those in this manual
 1670: (@pxref{Word Index}).
 1671: @end quotation
 1672: 
 1673: Sometimes programmers put comments at various places in colon
 1674: definitions that describe the contents of the stack at that place (stack
 1675: comments); i.e., they are like the first part of a stack-effect
 1676: comment. E.g.,
 1677: 
 1678: @example
 1679: : cubed ( n -- n^3 )
 1680:    dup squared  ( n n^2 ) * ;
 1681: @end example
 1682: 
 1683: In this case the stack comment is pretty superfluous, because the word
 1684: is simple enough.  If you think it would be a good idea to add such a
 1685: comment to increase readability, you should also consider factoring the
 1686: word into several simpler words (@pxref{Factoring Tutorial,,
 1687: Factoring}), which typically eliminates the need for the stack comment;
 1688: however, if you decide not to refactor it, then having such a comment is
 1689: better than not having it.
 1690: 
 1691: The names of the stack items in stack-effect and stack comments in the
 1692: standard, in this manual, and in many programs specify the type through
 1693: a type prefix, similar to Fortran and Hungarian notation.  The most
 1694: frequent prefixes are:
 1695: 
 1696: @table @code
 1697: @item n
 1698: signed integer
 1699: @item u
 1700: unsigned integer
 1701: @item c
 1702: character
 1703: @item f
 1704: Boolean flags, i.e. @code{false} or @code{true}.
 1705: @item a-addr,a-
 1706: Cell-aligned address
 1707: @item c-addr,c-
 1708: Char-aligned address (note that a Char may have two bytes in Windows NT)
 1709: @item xt
 1710: Execution token, same size as Cell
 1711: @item w,x
 1712: Cell, can contain an integer or an address.  It usually takes 32, 64 or
 1713: 16 bits (depending on your platform and Forth system). A cell is more
 1714: commonly known as machine word, but the term @emph{word} already means
 1715: something different in Forth.
 1716: @item d
 1717: signed double-cell integer
 1718: @item ud
 1719: unsigned double-cell integer
 1720: @item r
 1721: Float (on the FP stack)
 1722: @end table
 1723: 
 1724: You can find a more complete list in @ref{Notation}.
 1725: 
 1726: @quotation Assignment
 1727: Write stack-effect comments for all definitions you have written up to
 1728: now.
 1729: @end quotation
 1730: 
 1731: 
 1732: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
 1733: @section Types
 1734: @cindex types tutorial
 1735: 
 1736: In Forth the names of the operations are not overloaded; so similar
 1737: operations on different types need different names; e.g., @code{+} adds
 1738: integers, and you have to use @code{f+} to add floating-point numbers.
 1739: The following prefixes are often used for related operations on
 1740: different types:
 1741: 
 1742: @table @code
 1743: @item (none)
 1744: signed integer
 1745: @item u
 1746: unsigned integer
 1747: @item c
 1748: character
 1749: @item d
 1750: signed double-cell integer
 1751: @item ud, du
 1752: unsigned double-cell integer
 1753: @item 2
 1754: two cells (not-necessarily double-cell numbers)
 1755: @item m, um
 1756: mixed single-cell and double-cell operations
 1757: @item f
 1758: floating-point (note that in stack comments @samp{f} represents flags,
 1759: and @samp{r} represents FP numbers; also, you need to include the
 1760: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
 1761: @end table
 1762: 
 1763: If there are no differences between the signed and the unsigned variant
 1764: (e.g., for @code{+}), there is only the prefix-less variant.
 1765: 
 1766: Forth does not perform type checking, neither at compile time, nor at
 1767: run time.  If you use the wrong operation, the data are interpreted
 1768: incorrectly:
 1769: 
 1770: @example
 1771: -1 u.
 1772: @end example
 1773: 
 1774: If you have only experience with type-checked languages until now, and
 1775: have heard how important type-checking is, don't panic!  In my
 1776: experience (and that of other Forthers), type errors in Forth code are
 1777: usually easy to find (once you get used to it), the increased vigilance
 1778: of the programmer tends to catch some harder errors in addition to most
 1779: type errors, and you never have to work around the type system, so in
 1780: most situations the lack of type-checking seems to be a win (projects to
 1781: add type checking to Forth have not caught on).
 1782: 
 1783: 
 1784: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
 1785: @section Factoring
 1786: @cindex factoring tutorial
 1787: 
 1788: If you try to write longer definitions, you will soon find it hard to
 1789: keep track of the stack contents.  Therefore, good Forth programmers
 1790: tend to write only short definitions (e.g., three lines).  The art of
 1791: finding meaningful short definitions is known as factoring (as in
 1792: factoring polynomials).
 1793: 
 1794: Well-factored programs offer additional advantages: smaller, more
 1795: general words, are easier to test and debug and can be reused more and
 1796: better than larger, specialized words.
 1797: 
 1798: So, if you run into difficulties with stack management, when writing
 1799: code, try to define meaningful factors for the word, and define the word
 1800: in terms of those.  Even if a factor contains only two words, it is
 1801: often helpful.
 1802: 
 1803: Good factoring is not easy, and it takes some practice to get the knack
 1804: for it; but even experienced Forth programmers often don't find the
 1805: right solution right away, but only when rewriting the program.  So, if
 1806: you don't come up with a good solution immediately, keep trying, don't
 1807: despair.
 1808: 
 1809: @c example !!
 1810: 
 1811: 
 1812: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
 1813: @section Designing the stack effect
 1814: @cindex Stack effect design, tutorial
 1815: @cindex design of stack effects, tutorial
 1816: 
 1817: In other languages you can use an arbitrary order of parameters for a
 1818: function; and since there is only one result, you don't have to deal with
 1819: the order of results, either.
 1820: 
 1821: In Forth (and other stack-based languages, e.g., PostScript) the
 1822: parameter and result order of a definition is important and should be
 1823: designed well.  The general guideline is to design the stack effect such
 1824: that the word is simple to use in most cases, even if that complicates
 1825: the implementation of the word.  Some concrete rules are:
 1826: 
 1827: @itemize @bullet
 1828: 
 1829: @item
 1830: Words consume all of their parameters (e.g., @code{.}).
 1831: 
 1832: @item
 1833: If there is a convention on the order of parameters (e.g., from
 1834: mathematics or another programming language), stick with it (e.g.,
 1835: @code{-}).
 1836: 
 1837: @item
 1838: If one parameter usually requires only a short computation (e.g., it is
 1839: a constant), pass it on the top of the stack.  Conversely, parameters
 1840: that usually require a long sequence of code to compute should be passed
 1841: as the bottom (i.e., first) parameter.  This makes the code easier to
 1842: read, because the reader does not need to keep track of the bottom item
 1843: through a long sequence of code (or, alternatively, through stack
 1844: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
 1845: address on top of the stack because it is usually simpler to compute
 1846: than the stored value (often the address is just a variable).
 1847: 
 1848: @item
 1849: Similarly, results that are usually consumed quickly should be returned
 1850: on the top of stack, whereas a result that is often used in long
 1851: computations should be passed as bottom result.  E.g., the file words
 1852: like @code{open-file} return the error code on the top of stack, because
 1853: it is usually consumed quickly by @code{throw}; moreover, the error code
 1854: has to be checked before doing anything with the other results.
 1855: 
 1856: @end itemize
 1857: 
 1858: These rules are just general guidelines, don't lose sight of the overall
 1859: goal to make the words easy to use.  E.g., if the convention rule
 1860: conflicts with the computation-length rule, you might decide in favour
 1861: of the convention if the word will be used rarely, and in favour of the
 1862: computation-length rule if the word will be used frequently (because
 1863: with frequent use the cost of breaking the computation-length rule would
 1864: be quite high, and frequent use makes it easier to remember an
 1865: unconventional order).
 1866: 
 1867: @c example !! structure package
 1868: 
 1869: 
 1870: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
 1871: @section Local Variables
 1872: @cindex local variables, tutorial
 1873: 
 1874: You can define local variables (@emph{locals}) in a colon definition:
 1875: 
 1876: @example
 1877: : swap @{ a b -- b a @}
 1878:   b a ;
 1879: 1 2 swap .s 2drop
 1880: @end example
 1881: 
 1882: (If your Forth system does not support this syntax, include
 1883: @file{compat/anslocal.fs} first).
 1884: 
 1885: In this example @code{@{ a b -- b a @}} is the locals definition; it
 1886: takes two cells from the stack, puts the top of stack in @code{b} and
 1887: the next stack element in @code{a}.  @code{--} starts a comment ending
 1888: with @code{@}}.  After the locals definition, using the name of the
 1889: local will push its value on the stack.  You can leave the comment
 1890: part (@code{-- b a}) away:
 1891: 
 1892: @example
 1893: : swap ( x1 x2 -- x2 x1 )
 1894:   @{ a b @} b a ;
 1895: @end example
 1896: 
 1897: In Gforth you can have several locals definitions, anywhere in a colon
 1898: definition; in contrast, in a standard program you can have only one
 1899: locals definition per colon definition, and that locals definition must
 1900: be outside any control structure.
 1901: 
 1902: With locals you can write slightly longer definitions without running
 1903: into stack trouble.  However, I recommend trying to write colon
 1904: definitions without locals for exercise purposes to help you gain the
 1905: essential factoring skills.
 1906: 
 1907: @quotation Assignment
 1908: Rewrite your definitions until now with locals
 1909: @end quotation
 1910: 
 1911: Reference: @ref{Locals}.
 1912: 
 1913: 
 1914: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
 1915: @section Conditional execution
 1916: @cindex conditionals, tutorial
 1917: @cindex if, tutorial
 1918: 
 1919: In Forth you can use control structures only inside colon definitions.
 1920: An @code{if}-structure looks like this:
 1921: 
 1922: @example
 1923: : abs ( n1 -- +n2 )
 1924:     dup 0 < if
 1925:         negate
 1926:     endif ;
 1927: 5 abs .
 1928: -5 abs .
 1929: @end example
 1930: 
 1931: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
 1932: the following code is performed, otherwise execution continues after the
 1933: @code{endif} (or @code{else}).  @code{<} compares the top two stack
 1934: elements and produces a flag:
 1935: 
 1936: @example
 1937: 1 2 < .
 1938: 2 1 < .
 1939: 1 1 < .
 1940: @end example
 1941: 
 1942: Actually the standard name for @code{endif} is @code{then}.  This
 1943: tutorial presents the examples using @code{endif}, because this is often
 1944: less confusing for people familiar with other programming languages
 1945: where @code{then} has a different meaning.  If your system does not have
 1946: @code{endif}, define it with
 1947: 
 1948: @example
 1949: : endif postpone then ; immediate
 1950: @end example
 1951: 
 1952: You can optionally use an @code{else}-part:
 1953: 
 1954: @example
 1955: : min ( n1 n2 -- n )
 1956:   2dup < if
 1957:     drop
 1958:   else
 1959:     nip
 1960:   endif ;
 1961: 2 3 min .
 1962: 3 2 min .
 1963: @end example
 1964: 
 1965: @quotation Assignment
 1966: Write @code{min} without @code{else}-part (hint: what's the definition
 1967: of @code{nip}?).
 1968: @end quotation
 1969: 
 1970: Reference: @ref{Selection}.
 1971: 
 1972: 
 1973: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
 1974: @section Flags and Comparisons
 1975: @cindex flags tutorial
 1976: @cindex comparison tutorial
 1977: 
 1978: In a false-flag all bits are clear (0 when interpreted as integer).  In
 1979: a canonical true-flag all bits are set (-1 as a twos-complement signed
 1980: integer); in many contexts (e.g., @code{if}) any non-zero value is
 1981: treated as true flag.
 1982: 
 1983: @example
 1984: false .
 1985: true .
 1986: true hex u. decimal
 1987: @end example
 1988: 
 1989: Comparison words produce canonical flags:
 1990: 
 1991: @example
 1992: 1 1 = .
 1993: 1 0= .
 1994: 0 1 < .
 1995: 0 0 < .
 1996: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
 1997: -1 1 < .
 1998: @end example
 1999: 
 2000: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
 2001: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
 2002: these combinations are standard (for details see the standard,
 2003: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
 2004: 
 2005: You can use @code{and or xor invert} as operations on canonical flags.
 2006: Actually they are bitwise operations:
 2007: 
 2008: @example
 2009: 1 2 and .
 2010: 1 2 or .
 2011: 1 3 xor .
 2012: 1 invert .
 2013: @end example
 2014: 
 2015: You can convert a zero/non-zero flag into a canonical flag with
 2016: @code{0<>} (and complement it on the way with @code{0=}).
 2017: 
 2018: @example
 2019: 1 0= .
 2020: 1 0<> .
 2021: @end example
 2022: 
 2023: You can use the all-bits-set feature of canonical flags and the bitwise
 2024: operation of the Boolean operations to avoid @code{if}s:
 2025: 
 2026: @example
 2027: : foo ( n1 -- n2 )
 2028:   0= if
 2029:     14
 2030:   else
 2031:     0
 2032:   endif ;
 2033: 0 foo .
 2034: 1 foo .
 2035: 
 2036: : foo ( n1 -- n2 )
 2037:   0= 14 and ;
 2038: 0 foo .
 2039: 1 foo .
 2040: @end example
 2041: 
 2042: @quotation Assignment
 2043: Write @code{min} without @code{if}.
 2044: @end quotation
 2045: 
 2046: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
 2047: @ref{Bitwise operations}.
 2048: 
 2049: 
 2050: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
 2051: @section General Loops
 2052: @cindex loops, indefinite, tutorial
 2053: 
 2054: The endless loop is the most simple one:
 2055: 
 2056: @example
 2057: : endless ( -- )
 2058:   0 begin
 2059:     dup . 1+
 2060:   again ;
 2061: endless
 2062: @end example
 2063: 
 2064: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
 2065: does nothing at run-time, @code{again} jumps back to @code{begin}.
 2066: 
 2067: A loop with one exit at any place looks like this:
 2068: 
 2069: @example
 2070: : log2 ( +n1 -- n2 )
 2071: \ logarithmus dualis of n1>0, rounded down to the next integer
 2072:   assert( dup 0> )
 2073:   2/ 0 begin
 2074:     over 0> while
 2075:       1+ swap 2/ swap
 2076:   repeat
 2077:   nip ;
 2078: 7 log2 .
 2079: 8 log2 .
 2080: @end example
 2081: 
 2082: At run-time @code{while} consumes a flag; if it is 0, execution
 2083: continues behind the @code{repeat}; if the flag is non-zero, execution
 2084: continues behind the @code{while}.  @code{Repeat} jumps back to
 2085: @code{begin}, just like @code{again}.
 2086: 
 2087: In Forth there are a number of combinations/abbreviations, like
 2088: @code{1+}.  However, @code{2/} is not one of them; it shifts its
 2089: argument right by one bit (arithmetic shift right), and viewed as
 2090: division that always rounds towards negative infinity (floored
 2091: division).  In contrast, @code{/} rounds towards zero on some systems
 2092: (not on default installations of gforth (>=0.7.0), however).
 2093: 
 2094: @example
 2095: -5 2 / . \ -2 or -3
 2096: -5 2/ .  \ -3
 2097: @end example
 2098: 
 2099: @code{assert(} is no standard word, but you can get it on systems other
 2100: than Gforth by including @file{compat/assert.fs}.  You can see what it
 2101: does by trying
 2102: 
 2103: @example
 2104: 0 log2 .
 2105: @end example
 2106: 
 2107: Here's a loop with an exit at the end:
 2108: 
 2109: @example
 2110: : log2 ( +n1 -- n2 )
 2111: \ logarithmus dualis of n1>0, rounded down to the next integer
 2112:   assert( dup 0 > )
 2113:   -1 begin
 2114:     1+ swap 2/ swap
 2115:     over 0 <=
 2116:   until
 2117:   nip ;
 2118: @end example
 2119: 
 2120: @code{Until} consumes a flag; if it is zero, execution continues at
 2121: the @code{begin}, otherwise after the @code{until}.
 2122: 
 2123: @quotation Assignment
 2124: Write a definition for computing the greatest common divisor.
 2125: @end quotation
 2126: 
 2127: Reference: @ref{Simple Loops}.
 2128: 
 2129: 
 2130: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
 2131: @section Counted loops
 2132: @cindex loops, counted, tutorial
 2133: 
 2134: @example
 2135: : ^ ( n1 u -- n )
 2136: \ n = the uth power of n1
 2137:   1 swap 0 u+do
 2138:     over *
 2139:   loop
 2140:   nip ;
 2141: 3 2 ^ .
 2142: 4 3 ^ .
 2143: @end example
 2144: 
 2145: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
 2146: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
 2147: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
 2148: times (or not at all, if @code{u3-u4<0}).
 2149: 
 2150: You can see the stack effect design rules at work in the stack effect of
 2151: the loop start words: Since the start value of the loop is more
 2152: frequently constant than the end value, the start value is passed on
 2153: the top-of-stack.
 2154: 
 2155: You can access the counter of a counted loop with @code{i}:
 2156: 
 2157: @example
 2158: : fac ( u -- u! )
 2159:   1 swap 1+ 1 u+do
 2160:     i *
 2161:   loop ;
 2162: 5 fac .
 2163: 7 fac .
 2164: @end example
 2165: 
 2166: There is also @code{+do}, which expects signed numbers (important for
 2167: deciding whether to enter the loop).
 2168: 
 2169: @quotation Assignment
 2170: Write a definition for computing the nth Fibonacci number.
 2171: @end quotation
 2172: 
 2173: You can also use increments other than 1:
 2174: 
 2175: @example
 2176: : up2 ( n1 n2 -- )
 2177:   +do
 2178:     i .
 2179:   2 +loop ;
 2180: 10 0 up2
 2181: 
 2182: : down2 ( n1 n2 -- )
 2183:   -do
 2184:     i .
 2185:   2 -loop ;
 2186: 0 10 down2
 2187: @end example
 2188: 
 2189: Reference: @ref{Counted Loops}.
 2190: 
 2191: 
 2192: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
 2193: @section Recursion
 2194: @cindex recursion tutorial
 2195: 
 2196: Usually the name of a definition is not visible in the definition; but
 2197: earlier definitions are usually visible:
 2198: 
 2199: @example
 2200: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
 2201: : / ( n1 n2 -- n )
 2202:   dup 0= if
 2203:     -10 throw \ report division by zero
 2204:   endif
 2205:   /           \ old version
 2206: ;
 2207: 1 0 /
 2208: @end example
 2209: 
 2210: For recursive definitions you can use @code{recursive} (non-standard) or
 2211: @code{recurse}:
 2212: 
 2213: @example
 2214: : fac1 ( n -- n! ) recursive
 2215:  dup 0> if
 2216:    dup 1- fac1 *
 2217:  else
 2218:    drop 1
 2219:  endif ;
 2220: 7 fac1 .
 2221: 
 2222: : fac2 ( n -- n! )
 2223:  dup 0> if
 2224:    dup 1- recurse *
 2225:  else
 2226:    drop 1
 2227:  endif ;
 2228: 8 fac2 .
 2229: @end example
 2230: 
 2231: @quotation Assignment
 2232: Write a recursive definition for computing the nth Fibonacci number.
 2233: @end quotation
 2234: 
 2235: Reference (including indirect recursion): @xref{Calls and returns}.
 2236: 
 2237: 
 2238: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
 2239: @section Leaving definitions or loops
 2240: @cindex leaving definitions, tutorial
 2241: @cindex leaving loops, tutorial
 2242: 
 2243: @code{EXIT} exits the current definition right away.  For every counted
 2244: loop that is left in this way, an @code{UNLOOP} has to be performed
 2245: before the @code{EXIT}:
 2246: 
 2247: @c !! real examples
 2248: @example
 2249: : ...
 2250:  ... u+do
 2251:    ... if
 2252:      ... unloop exit
 2253:    endif
 2254:    ...
 2255:  loop
 2256:  ... ;
 2257: @end example
 2258: 
 2259: @code{LEAVE} leaves the innermost counted loop right away:
 2260: 
 2261: @example
 2262: : ...
 2263:  ... u+do
 2264:    ... if
 2265:      ... leave
 2266:    endif
 2267:    ...
 2268:  loop
 2269:  ... ;
 2270: @end example
 2271: 
 2272: @c !! example
 2273: 
 2274: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
 2275: 
 2276: 
 2277: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
 2278: @section Return Stack
 2279: @cindex return stack tutorial
 2280: 
 2281: In addition to the data stack Forth also has a second stack, the return
 2282: stack; most Forth systems store the return addresses of procedure calls
 2283: there (thus its name).  Programmers can also use this stack:
 2284: 
 2285: @example
 2286: : foo ( n1 n2 -- )
 2287:  .s
 2288:  >r .s
 2289:  r@@ .
 2290:  >r .s
 2291:  r@@ .
 2292:  r> .
 2293:  r@@ .
 2294:  r> . ;
 2295: 1 2 foo
 2296: @end example
 2297: 
 2298: @code{>r} takes an element from the data stack and pushes it onto the
 2299: return stack; conversely, @code{r>} moves an elementm from the return to
 2300: the data stack; @code{r@@} pushes a copy of the top of the return stack
 2301: on the data stack.
 2302: 
 2303: Forth programmers usually use the return stack for storing data
 2304: temporarily, if using the data stack alone would be too complex, and
 2305: factoring and locals are not an option:
 2306: 
 2307: @example
 2308: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
 2309:  rot >r rot r> ;
 2310: @end example
 2311: 
 2312: The return address of the definition and the loop control parameters of
 2313: counted loops usually reside on the return stack, so you have to take
 2314: all items, that you have pushed on the return stack in a colon
 2315: definition or counted loop, from the return stack before the definition
 2316: or loop ends.  You cannot access items that you pushed on the return
 2317: stack outside some definition or loop within the definition of loop.
 2318: 
 2319: If you miscount the return stack items, this usually ends in a crash:
 2320: 
 2321: @example
 2322: : crash ( n -- )
 2323:   >r ;
 2324: 5 crash
 2325: @end example
 2326: 
 2327: You cannot mix using locals and using the return stack (according to the
 2328: standard; Gforth has no problem).  However, they solve the same
 2329: problems, so this shouldn't be an issue.
 2330: 
 2331: @quotation Assignment
 2332: Can you rewrite any of the definitions you wrote until now in a better
 2333: way using the return stack?
 2334: @end quotation
 2335: 
 2336: Reference: @ref{Return stack}.
 2337: 
 2338: 
 2339: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
 2340: @section Memory
 2341: @cindex memory access/allocation tutorial
 2342: 
 2343: You can create a global variable @code{v} with
 2344: 
 2345: @example
 2346: variable v ( -- addr )
 2347: @end example
 2348: 
 2349: @code{v} pushes the address of a cell in memory on the stack.  This cell
 2350: was reserved by @code{variable}.  You can use @code{!} (store) to store
 2351: values into this cell and @code{@@} (fetch) to load the value from the
 2352: stack into memory:
 2353: 
 2354: @example
 2355: v .
 2356: 5 v ! .s
 2357: v @@ .
 2358: @end example
 2359: 
 2360: You can see a raw dump of memory with @code{dump}:
 2361: 
 2362: @example
 2363: v 1 cells .s dump
 2364: @end example
 2365: 
 2366: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
 2367: generally, address units (aus)) that @code{n1 cells} occupy.  You can
 2368: also reserve more memory:
 2369: 
 2370: @example
 2371: create v2 20 cells allot
 2372: v2 20 cells dump
 2373: @end example
 2374: 
 2375: creates a variable-like word @code{v2} and reserves 20 uninitialized
 2376: cells; the address pushed by @code{v2} points to the start of these 20
 2377: cells (@pxref{CREATE}).  You can use address arithmetic to access
 2378: these cells:
 2379: 
 2380: @example
 2381: 3 v2 5 cells + !
 2382: v2 20 cells dump
 2383: @end example
 2384: 
 2385: You can reserve and initialize memory with @code{,}:
 2386: 
 2387: @example
 2388: create v3
 2389:   5 , 4 , 3 , 2 , 1 ,
 2390: v3 @@ .
 2391: v3 cell+ @@ .
 2392: v3 2 cells + @@ .
 2393: v3 5 cells dump
 2394: @end example
 2395: 
 2396: @quotation Assignment
 2397: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
 2398: @code{u} cells, with the first of these cells at @code{addr}, the next
 2399: one at @code{addr cell+} etc.
 2400: @end quotation
 2401: 
 2402: The difference between @code{variable} and @code{create} is that
 2403: @code{variable} allots a cell, and that you cannot allot additional
 2404: memory to a variable in standard Forth.
 2405: 
 2406: You can also reserve memory without creating a new word:
 2407: 
 2408: @example
 2409: here 10 cells allot .
 2410: here .
 2411: @end example
 2412: 
 2413: The first @code{here} pushes the start address of the memory area, the
 2414: second @code{here} the address after the dictionary area.  You should
 2415: store the start address somewhere, or you will have a hard time
 2416: finding the memory area again.
 2417: 
 2418: @code{Allot} manages dictionary memory.  The dictionary memory contains
 2419: the system's data structures for words etc. on Gforth and most other
 2420: Forth systems.  It is managed like a stack: You can free the memory that
 2421: you have just @code{allot}ed with
 2422: 
 2423: @example
 2424: -10 cells allot
 2425: here .
 2426: @end example
 2427: 
 2428: Note that you cannot do this if you have created a new word in the
 2429: meantime (because then your @code{allot}ed memory is no longer on the
 2430: top of the dictionary ``stack'').
 2431: 
 2432: Alternatively, you can use @code{allocate} and @code{free} which allow
 2433: freeing memory in any order:
 2434: 
 2435: @example
 2436: 10 cells allocate throw .s
 2437: 20 cells allocate throw .s
 2438: swap
 2439: free throw
 2440: free throw
 2441: @end example
 2442: 
 2443: The @code{throw}s deal with errors (e.g., out of memory).
 2444: 
 2445: And there is also a
 2446: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 2447: garbage collector}, which eliminates the need to @code{free} memory
 2448: explicitly.
 2449: 
 2450: Reference: @ref{Memory}.
 2451: 
 2452: 
 2453: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
 2454: @section Characters and Strings
 2455: @cindex strings tutorial
 2456: @cindex characters tutorial
 2457: 
 2458: On the stack characters take up a cell, like numbers.  In memory they
 2459: have their own size (one 8-bit byte on most systems), and therefore
 2460: require their own words for memory access:
 2461: 
 2462: @example
 2463: create v4 
 2464:   104 c, 97 c, 108 c, 108 c, 111 c,
 2465: v4 4 chars + c@@ .
 2466: v4 5 chars dump
 2467: @end example
 2468: 
 2469: The preferred representation of strings on the stack is @code{addr
 2470: u-count}, where @code{addr} is the address of the first character and
 2471: @code{u-count} is the number of characters in the string.
 2472: 
 2473: @example
 2474: v4 5 type
 2475: @end example
 2476: 
 2477: You get a string constant with
 2478: 
 2479: @example
 2480: s" hello, world" .s
 2481: type
 2482: @end example
 2483: 
 2484: Make sure you have a space between @code{s"} and the string; @code{s"}
 2485: is a normal Forth word and must be delimited with white space (try what
 2486: happens when you remove the space).
 2487: 
 2488: However, this interpretive use of @code{s"} is quite restricted: the
 2489: string exists only until the next call of @code{s"} (some Forth systems
 2490: keep more than one of these strings, but usually they still have a
 2491: limited lifetime).
 2492: 
 2493: @example
 2494: s" hello," s" world" .s
 2495: type
 2496: type
 2497: @end example
 2498: 
 2499: You can also use @code{s"} in a definition, and the resulting
 2500: strings then live forever (well, for as long as the definition):
 2501: 
 2502: @example
 2503: : foo s" hello," s" world" ;
 2504: foo .s
 2505: type
 2506: type
 2507: @end example
 2508: 
 2509: @quotation Assignment
 2510: @code{Emit ( c -- )} types @code{c} as character (not a number).
 2511: Implement @code{type ( addr u -- )}.
 2512: @end quotation
 2513: 
 2514: Reference: @ref{Memory Blocks}.
 2515: 
 2516: 
 2517: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
 2518: @section Alignment
 2519: @cindex alignment tutorial
 2520: @cindex memory alignment tutorial
 2521: 
 2522: On many processors cells have to be aligned in memory, if you want to
 2523: access them with @code{@@} and @code{!} (and even if the processor does
 2524: not require alignment, access to aligned cells is faster).
 2525: 
 2526: @code{Create} aligns @code{here} (i.e., the place where the next
 2527: allocation will occur, and that the @code{create}d word points to).
 2528: Likewise, the memory produced by @code{allocate} starts at an aligned
 2529: address.  Adding a number of @code{cells} to an aligned address produces
 2530: another aligned address.
 2531: 
 2532: However, address arithmetic involving @code{char+} and @code{chars} can
 2533: create an address that is not cell-aligned.  @code{Aligned ( addr --
 2534: a-addr )} produces the next aligned address:
 2535: 
 2536: @example
 2537: v3 char+ aligned .s @@ .
 2538: v3 char+ .s @@ .
 2539: @end example
 2540: 
 2541: Similarly, @code{align} advances @code{here} to the next aligned
 2542: address:
 2543: 
 2544: @example
 2545: create v5 97 c,
 2546: here .
 2547: align here .
 2548: 1000 ,
 2549: @end example
 2550: 
 2551: Note that you should use aligned addresses even if your processor does
 2552: not require them, if you want your program to be portable.
 2553: 
 2554: Reference: @ref{Address arithmetic}.
 2555: 
 2556: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
 2557: @section Floating Point
 2558: @cindex floating point tutorial
 2559: @cindex FP tutorial
 2560: 
 2561: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
 2562: might expect, but there are a few things worth noting:
 2563: 
 2564: The first point is not specific to Forth, but so important and yet not
 2565: universally known that I mention it here: FP numbers are not reals.
 2566: Many properties (e.g., arithmetic laws) that reals have and that one
 2567: expects of all kinds of numbers do not hold for FP numbers.  If you
 2568: want to use FP computations, you should learn about their problems and
 2569: how to avoid them; a good starting point is @cite{David Goldberg,
 2570: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 2571: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 2572: Computing Surveys 23(1):5@minus{}48, March 1991}.
 2573: 
 2574: In Forth source code literal FP numbers need an exponent, e.g.,
 2575: @code{1e0}; this can also be written shorter as @code{1e}, longer as
 2576: @code{+1.0e+0}, and many variations in between.  The reason for this is
 2577: that, for historical reasons, Forth interprets a decimal point alone
 2578: (e.g., @code{1.}) as indicating a double-cell integer.  Examples:
 2579: 
 2580: @example
 2581: 2e 2e f+ f.
 2582: @end example
 2583: 
 2584: Another requirement for literal FP numbers is that the current base is
 2585: decimal; with a hex base @code{1e} is interpreted as an integer.
 2586: 
 2587: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
 2588: ANS Forth system may implement the FP stack on the data stack, but
 2589: virtually all systems implement a separate FP stack; and programming
 2590: in a way that accommodates all models is so cumbersome that nobody
 2591: does it.}  One advantage of this model is that cells are not in the
 2592: way when accessing FP values, and vice versa.  Forth has a set of
 2593: words for manipulating the FP stack: @code{fdup fswap fdrop fover
 2594: frot} and (non-standard) @code{fnip ftuck fpick}.
 2595: 
 2596: FP arithmetic words are prefixed with @code{F}.  There is the usual
 2597: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
 2598: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
 2599: might expect is @code{f=}; but @code{f=} is non-standard, because FP
 2600: computation results are usually inaccurate, so exact comparison is
 2601: usually a mistake, and one should use approximate comparison.
 2602: Unfortunately, @code{f~}, the standard word for that purpose, is not
 2603: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
 2604: well.
 2605: 
 2606: And of course there are words for accessing FP numbers in memory
 2607: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
 2608: faligned}).  There are also variants of these words with an @code{sf}
 2609: and @code{df} prefix for accessing IEEE format single-precision and
 2610: double-precision numbers in memory; their main purpose is for
 2611: accessing external FP data (e.g., that has been read from or will be
 2612: written to a file).
 2613: 
 2614: Here is an example of a dot-product word and its use:
 2615: 
 2616: @example
 2617: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 2618:   >r swap 2swap swap 0e r> 0 ?DO
 2619:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 2620:   LOOP
 2621:   2drop 2drop ;
 2622: 
 2623: create v 1.23e f, 4.56e f, 7.89e f,
 2624: 
 2625: v 1 floats  v 1 floats  3  v* f.
 2626: @end example
 2627: 
 2628: @quotation Assignment
 2629: Write a program to solve a quadratic equation.  Then read @cite{Henry
 2630: G. Baker,
 2631: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
 2632: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
 2633: 33(1):30@minus{}39, January 1998}, and see if you can improve your
 2634: program.  Finally, find a test case where the original and the
 2635: improved version produce different results.
 2636: @end quotation
 2637: 
 2638: Reference: @ref{Floating Point}; @ref{Floating point stack};
 2639: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
 2640: arithmetic}.
 2641: 
 2642: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
 2643: @section Files
 2644: @cindex files tutorial
 2645: 
 2646: This section gives a short introduction into how to use files inside
 2647: Forth. It's broken up into five easy steps:
 2648: 
 2649: @enumerate 1
 2650: @item Opened an ASCII text file for input
 2651: @item Opened a file for output
 2652: @item Read input file until string matched (or some other condition matched)
 2653: @item Wrote some lines from input ( modified or not) to output
 2654: @item Closed the files.
 2655: @end enumerate
 2656: 
 2657: Reference: @ref{General files}.
 2658: 
 2659: @subsection Open file for input
 2660: 
 2661: @example
 2662: s" foo.in"  r/o open-file throw Value fd-in
 2663: @end example
 2664: 
 2665: @subsection Create file for output
 2666: 
 2667: @example
 2668: s" foo.out" w/o create-file throw Value fd-out
 2669: @end example
 2670: 
 2671: The available file modes are r/o for read-only access, r/w for
 2672: read-write access, and w/o for write-only access. You could open both
 2673: files with r/w, too, if you like. All file words return error codes; for
 2674: most applications, it's best to pass there error codes with @code{throw}
 2675: to the outer error handler.
 2676: 
 2677: If you want words for opening and assigning, define them as follows:
 2678: 
 2679: @example
 2680: 0 Value fd-in
 2681: 0 Value fd-out
 2682: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
 2683: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
 2684: @end example
 2685: 
 2686: Usage example:
 2687: 
 2688: @example
 2689: s" foo.in" open-input
 2690: s" foo.out" open-output
 2691: @end example
 2692: 
 2693: @subsection Scan file for a particular line
 2694: 
 2695: @example
 2696: 256 Constant max-line
 2697: Create line-buffer  max-line 2 + allot
 2698: 
 2699: : scan-file ( addr u -- )
 2700:   begin
 2701:       line-buffer max-line fd-in read-line throw
 2702:   while
 2703:          >r 2dup line-buffer r> compare 0=
 2704:      until
 2705:   else
 2706:      drop
 2707:   then
 2708:   2drop ;
 2709: @end example
 2710: 
 2711: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
 2712: the buffer at addr, and returns the number of bytes read, a flag that is
 2713: false when the end of file is reached, and an error code.
 2714: 
 2715: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
 2716: returns zero if both strings are equal. It returns a positive number if
 2717: the first string is lexically greater, a negative if the second string
 2718: is lexically greater.
 2719: 
 2720: We haven't seen this loop here; it has two exits. Since the @code{while}
 2721: exits with the number of bytes read on the stack, we have to clean up
 2722: that separately; that's after the @code{else}.
 2723: 
 2724: Usage example:
 2725: 
 2726: @example
 2727: s" The text I search is here" scan-file
 2728: @end example
 2729: 
 2730: @subsection Copy input to output
 2731: 
 2732: @example
 2733: : copy-file ( -- )
 2734:   begin
 2735:       line-buffer max-line fd-in read-line throw
 2736:   while
 2737:       line-buffer swap fd-out write-line throw
 2738:   repeat 
 2739:   drop ;
 2740: @end example
 2741: @c !! does not handle long lines, no newline at end of file
 2742: 
 2743: @subsection Close files
 2744: 
 2745: @example
 2746: fd-in close-file throw
 2747: fd-out close-file throw
 2748: @end example
 2749: 
 2750: Likewise, you can put that into definitions, too:
 2751: 
 2752: @example
 2753: : close-input ( -- )  fd-in close-file throw ;
 2754: : close-output ( -- )  fd-out close-file throw ;
 2755: @end example
 2756: 
 2757: @quotation Assignment
 2758: How could you modify @code{copy-file} so that it copies until a second line is
 2759: matched? Can you write a program that extracts a section of a text file,
 2760: given the line that starts and the line that terminates that section?
 2761: @end quotation
 2762: 
 2763: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
 2764: @section Interpretation and Compilation Semantics and Immediacy
 2765: @cindex semantics tutorial
 2766: @cindex interpretation semantics tutorial
 2767: @cindex compilation semantics tutorial
 2768: @cindex immediate, tutorial
 2769: 
 2770: When a word is compiled, it behaves differently from being interpreted.
 2771: E.g., consider @code{+}:
 2772: 
 2773: @example
 2774: 1 2 + .
 2775: : foo + ;
 2776: @end example
 2777: 
 2778: These two behaviours are known as compilation and interpretation
 2779: semantics.  For normal words (e.g., @code{+}), the compilation semantics
 2780: is to append the interpretation semantics to the currently defined word
 2781: (@code{foo} in the example above).  I.e., when @code{foo} is executed
 2782: later, the interpretation semantics of @code{+} (i.e., adding two
 2783: numbers) will be performed.
 2784: 
 2785: However, there are words with non-default compilation semantics, e.g.,
 2786: the control-flow words like @code{if}.  You can use @code{immediate} to
 2787: change the compilation semantics of the last defined word to be equal to
 2788: the interpretation semantics:
 2789: 
 2790: @example
 2791: : [FOO] ( -- )
 2792:  5 . ; immediate
 2793: 
 2794: [FOO]
 2795: : bar ( -- )
 2796:   [FOO] ;
 2797: bar
 2798: see bar
 2799: @end example
 2800: 
 2801: Two conventions to mark words with non-default compilation semantics are
 2802: names with brackets (more frequently used) and to write them all in
 2803: upper case (less frequently used).
 2804: 
 2805: In Gforth (and many other systems) you can also remove the
 2806: interpretation semantics with @code{compile-only} (the compilation
 2807: semantics is derived from the original interpretation semantics):
 2808: 
 2809: @example
 2810: : flip ( -- )
 2811:  6 . ; compile-only \ but not immediate
 2812: flip
 2813: 
 2814: : flop ( -- )
 2815:  flip ;
 2816: flop
 2817: @end example
 2818: 
 2819: In this example the interpretation semantics of @code{flop} is equal to
 2820: the original interpretation semantics of @code{flip}.
 2821: 
 2822: The text interpreter has two states: in interpret state, it performs the
 2823: interpretation semantics of words it encounters; in compile state, it
 2824: performs the compilation semantics of these words.
 2825: 
 2826: Among other things, @code{:} switches into compile state, and @code{;}
 2827: switches back to interpret state.  They contain the factors @code{]}
 2828: (switch to compile state) and @code{[} (switch to interpret state), that
 2829: do nothing but switch the state.
 2830: 
 2831: @example
 2832: : xxx ( -- )
 2833:   [ 5 . ]
 2834: ;
 2835: 
 2836: xxx
 2837: see xxx
 2838: @end example
 2839: 
 2840: These brackets are also the source of the naming convention mentioned
 2841: above.
 2842: 
 2843: Reference: @ref{Interpretation and Compilation Semantics}.
 2844: 
 2845: 
 2846: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
 2847: @section Execution Tokens
 2848: @cindex execution tokens tutorial
 2849: @cindex XT tutorial
 2850: 
 2851: @code{' word} gives you the execution token (XT) of a word.  The XT is a
 2852: cell representing the interpretation semantics of a word.  You can
 2853: execute this semantics with @code{execute}:
 2854: 
 2855: @example
 2856: ' + .s
 2857: 1 2 rot execute .
 2858: @end example
 2859: 
 2860: The XT is similar to a function pointer in C.  However, parameter
 2861: passing through the stack makes it a little more flexible:
 2862: 
 2863: @example
 2864: : map-array ( ... addr u xt -- ... )
 2865: \ executes xt ( ... x -- ... ) for every element of the array starting
 2866: \ at addr and containing u elements
 2867:   @{ xt @}
 2868:   cells over + swap ?do
 2869:     i @@ xt execute
 2870:   1 cells +loop ;
 2871: 
 2872: create a 3 , 4 , 2 , -1 , 4 ,
 2873: a 5 ' . map-array .s
 2874: 0 a 5 ' + map-array .
 2875: s" max-n" environment? drop .s
 2876: a 5 ' min map-array .
 2877: @end example
 2878: 
 2879: You can use map-array with the XTs of words that consume one element
 2880: more than they produce.  In theory you can also use it with other XTs,
 2881: but the stack effect then depends on the size of the array, which is
 2882: hard to understand.
 2883: 
 2884: Since XTs are cell-sized, you can store them in memory and manipulate
 2885: them on the stack like other cells.  You can also compile the XT into a
 2886: word with @code{compile,}:
 2887: 
 2888: @example
 2889: : foo1 ( n1 n2 -- n )
 2890:    [ ' + compile, ] ;
 2891: see foo1
 2892: @end example
 2893: 
 2894: This is non-standard, because @code{compile,} has no compilation
 2895: semantics in the standard, but it works in good Forth systems.  For the
 2896: broken ones, use
 2897: 
 2898: @example
 2899: : [compile,] compile, ; immediate
 2900: 
 2901: : foo1 ( n1 n2 -- n )
 2902:    [ ' + ] [compile,] ;
 2903: see foo
 2904: @end example
 2905: 
 2906: @code{'} is a word with default compilation semantics; it parses the
 2907: next word when its interpretation semantics are executed, not during
 2908: compilation:
 2909: 
 2910: @example
 2911: : foo ( -- xt )
 2912:   ' ;
 2913: see foo
 2914: : bar ( ... "word" -- ... )
 2915:   ' execute ;
 2916: see bar
 2917: 1 2 bar + .
 2918: @end example
 2919: 
 2920: You often want to parse a word during compilation and compile its XT so
 2921: it will be pushed on the stack at run-time.  @code{[']} does this:
 2922: 
 2923: @example
 2924: : xt-+ ( -- xt )
 2925:   ['] + ;
 2926: see xt-+
 2927: 1 2 xt-+ execute .
 2928: @end example
 2929: 
 2930: Many programmers tend to see @code{'} and the word it parses as one
 2931: unit, and expect it to behave like @code{[']} when compiled, and are
 2932: confused by the actual behaviour.  If you are, just remember that the
 2933: Forth system just takes @code{'} as one unit and has no idea that it is
 2934: a parsing word (attempts to convenience programmers in this issue have
 2935: usually resulted in even worse pitfalls, see
 2936: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
 2937: @code{State}-smartness---Why it is evil and How to Exorcise it}).
 2938: 
 2939: Note that the state of the interpreter does not come into play when
 2940: creating and executing XTs.  I.e., even when you execute @code{'} in
 2941: compile state, it still gives you the interpretation semantics.  And
 2942: whatever that state is, @code{execute} performs the semantics
 2943: represented by the XT (i.e., for XTs produced with @code{'} the
 2944: interpretation semantics).
 2945: 
 2946: Reference: @ref{Tokens for Words}.
 2947: 
 2948: 
 2949: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
 2950: @section Exceptions
 2951: @cindex exceptions tutorial
 2952: 
 2953: @code{throw ( n -- )} causes an exception unless n is zero.
 2954: 
 2955: @example
 2956: 100 throw .s
 2957: 0 throw .s
 2958: @end example
 2959: 
 2960: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
 2961: it catches exceptions and pushes the number of the exception on the
 2962: stack (or 0, if the xt executed without exception).  If there was an
 2963: exception, the stacks have the same depth as when entering @code{catch}:
 2964: 
 2965: @example
 2966: .s
 2967: 3 0 ' / catch .s
 2968: 3 2 ' / catch .s
 2969: @end example
 2970: 
 2971: @quotation Assignment
 2972: Try the same with @code{execute} instead of @code{catch}.
 2973: @end quotation
 2974: 
 2975: @code{Throw} always jumps to the dynamically next enclosing
 2976: @code{catch}, even if it has to leave several call levels to achieve
 2977: this:
 2978: 
 2979: @example
 2980: : foo 100 throw ;
 2981: : foo1 foo ." after foo" ;
 2982: : bar ['] foo1 catch ;
 2983: bar .
 2984: @end example
 2985: 
 2986: It is often important to restore a value upon leaving a definition, even
 2987: if the definition is left through an exception.  You can ensure this
 2988: like this:
 2989: 
 2990: @example
 2991: : ...
 2992:    save-x
 2993:    ['] word-changing-x catch ( ... n )
 2994:    restore-x
 2995:    ( ... n ) throw ;
 2996: @end example
 2997: 
 2998: However, this is still not safe against, e.g., the user pressing
 2999: @kbd{Ctrl-C} when execution is between the @code{catch} and
 3000: @code{restore-x}.
 3001: 
 3002: Gforth provides an alternative exception handling syntax that is safe
 3003: against such cases: @code{try ... restore ... endtry}.  If the code
 3004: between @code{try} and @code{endtry} has an exception, the stack
 3005: depths are restored, the exception number is pushed on the stack, and
 3006: the execution continues right after @code{restore}.
 3007: 
 3008: The safer equivalent to the restoration code above is
 3009: 
 3010: @example
 3011: : ...
 3012:   save-x
 3013:   try
 3014:     word-changing-x 0
 3015:   restore
 3016:     restore-x
 3017:   endtry
 3018:   throw ;
 3019: @end example
 3020: 
 3021: Reference: @ref{Exception Handling}.
 3022: 
 3023: 
 3024: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
 3025: @section Defining Words
 3026: @cindex defining words tutorial
 3027: @cindex does> tutorial
 3028: @cindex create...does> tutorial
 3029: 
 3030: @c before semantics?
 3031: 
 3032: @code{:}, @code{create}, and @code{variable} are definition words: They
 3033: define other words.  @code{Constant} is another definition word:
 3034: 
 3035: @example
 3036: 5 constant foo
 3037: foo .
 3038: @end example
 3039: 
 3040: You can also use the prefixes @code{2} (double-cell) and @code{f}
 3041: (floating point) with @code{variable} and @code{constant}.
 3042: 
 3043: You can also define your own defining words.  E.g.:
 3044: 
 3045: @example
 3046: : variable ( "name" -- )
 3047:   create 0 , ;
 3048: @end example
 3049: 
 3050: You can also define defining words that create words that do something
 3051: other than just producing their address:
 3052: 
 3053: @example
 3054: : constant ( n "name" -- )
 3055:   create ,
 3056: does> ( -- n )
 3057:   ( addr ) @@ ;
 3058: 
 3059: 5 constant foo
 3060: foo .
 3061: @end example
 3062: 
 3063: The definition of @code{constant} above ends at the @code{does>}; i.e.,
 3064: @code{does>} replaces @code{;}, but it also does something else: It
 3065: changes the last defined word such that it pushes the address of the
 3066: body of the word and then performs the code after the @code{does>}
 3067: whenever it is called.
 3068: 
 3069: In the example above, @code{constant} uses @code{,} to store 5 into the
 3070: body of @code{foo}.  When @code{foo} executes, it pushes the address of
 3071: the body onto the stack, then (in the code after the @code{does>})
 3072: fetches the 5 from there.
 3073: 
 3074: The stack comment near the @code{does>} reflects the stack effect of the
 3075: defined word, not the stack effect of the code after the @code{does>}
 3076: (the difference is that the code expects the address of the body that
 3077: the stack comment does not show).
 3078: 
 3079: You can use these definition words to do factoring in cases that involve
 3080: (other) definition words.  E.g., a field offset is always added to an
 3081: address.  Instead of defining
 3082: 
 3083: @example
 3084: 2 cells constant offset-field1
 3085: @end example
 3086: 
 3087: and using this like
 3088: 
 3089: @example
 3090: ( addr ) offset-field1 +
 3091: @end example
 3092: 
 3093: you can define a definition word
 3094: 
 3095: @example
 3096: : simple-field ( n "name" -- )
 3097:   create ,
 3098: does> ( n1 -- n1+n )
 3099:   ( addr ) @@ + ;
 3100: @end example
 3101: 
 3102: Definition and use of field offsets now look like this:
 3103: 
 3104: @example
 3105: 2 cells simple-field field1
 3106: create mystruct 4 cells allot
 3107: mystruct .s field1 .s drop
 3108: @end example
 3109: 
 3110: If you want to do something with the word without performing the code
 3111: after the @code{does>}, you can access the body of a @code{create}d word
 3112: with @code{>body ( xt -- addr )}:
 3113: 
 3114: @example
 3115: : value ( n "name" -- )
 3116:   create ,
 3117: does> ( -- n1 )
 3118:   @@ ;
 3119: : to ( n "name" -- )
 3120:   ' >body ! ;
 3121: 
 3122: 5 value foo
 3123: foo .
 3124: 7 to foo
 3125: foo .
 3126: @end example
 3127: 
 3128: @quotation Assignment
 3129: Define @code{defer ( "name" -- )}, which creates a word that stores an
 3130: XT (at the start the XT of @code{abort}), and upon execution
 3131: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
 3132: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
 3133: recursion is one application of @code{defer}.
 3134: @end quotation
 3135: 
 3136: Reference: @ref{User-defined Defining Words}.
 3137: 
 3138: 
 3139: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
 3140: @section Arrays and Records
 3141: @cindex arrays tutorial
 3142: @cindex records tutorial
 3143: @cindex structs tutorial
 3144: 
 3145: Forth has no standard words for defining data structures such as arrays
 3146: and records (structs in C terminology), but you can build them yourself
 3147: based on address arithmetic.  You can also define words for defining
 3148: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
 3149: 
 3150: One of the first projects a Forth newcomer sets out upon when learning
 3151: about defining words is an array defining word (possibly for
 3152: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
 3153: learn something from it.  However, don't be disappointed when you later
 3154: learn that you have little use for these words (inappropriate use would
 3155: be even worse).  I have not found a set of useful array words yet;
 3156: the needs are just too diverse, and named, global arrays (the result of
 3157: naive use of defining words) are often not flexible enough (e.g.,
 3158: consider how to pass them as parameters).  Another such project is a set
 3159: of words to help dealing with strings.
 3160: 
 3161: On the other hand, there is a useful set of record words, and it has
 3162: been defined in @file{compat/struct.fs}; these words are predefined in
 3163: Gforth.  They are explained in depth elsewhere in this manual (see
 3164: @pxref{Structures}).  The @code{simple-field} example above is
 3165: simplified variant of fields in this package.
 3166: 
 3167: 
 3168: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
 3169: @section @code{POSTPONE}
 3170: @cindex postpone tutorial
 3171: 
 3172: You can compile the compilation semantics (instead of compiling the
 3173: interpretation semantics) of a word with @code{POSTPONE}:
 3174: 
 3175: @example
 3176: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3177:  POSTPONE + ; immediate
 3178: : foo ( n1 n2 -- n )
 3179:  MY-+ ;
 3180: 1 2 foo .
 3181: see foo
 3182: @end example
 3183: 
 3184: During the definition of @code{foo} the text interpreter performs the
 3185: compilation semantics of @code{MY-+}, which performs the compilation
 3186: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
 3187: 
 3188: This example also displays separate stack comments for the compilation
 3189: semantics and for the stack effect of the compiled code.  For words with
 3190: default compilation semantics these stack effects are usually not
 3191: displayed; the stack effect of the compilation semantics is always
 3192: @code{( -- )} for these words, the stack effect for the compiled code is
 3193: the stack effect of the interpretation semantics.
 3194: 
 3195: Note that the state of the interpreter does not come into play when
 3196: performing the compilation semantics in this way.  You can also perform
 3197: it interpretively, e.g.:
 3198: 
 3199: @example
 3200: : foo2 ( n1 n2 -- n )
 3201:  [ MY-+ ] ;
 3202: 1 2 foo .
 3203: see foo
 3204: @end example
 3205: 
 3206: However, there are some broken Forth systems where this does not always
 3207: work, and therefore this practice was been declared non-standard in
 3208: 1999.
 3209: @c !! repair.fs
 3210: 
 3211: Here is another example for using @code{POSTPONE}:
 3212: 
 3213: @example
 3214: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
 3215:  POSTPONE negate POSTPONE + ; immediate compile-only
 3216: : bar ( n1 n2 -- n )
 3217:   MY-- ;
 3218: 2 1 bar .
 3219: see bar
 3220: @end example
 3221: 
 3222: You can define @code{ENDIF} in this way:
 3223: 
 3224: @example
 3225: : ENDIF ( Compilation: orig -- )
 3226:   POSTPONE then ; immediate
 3227: @end example
 3228: 
 3229: @quotation Assignment
 3230: Write @code{MY-2DUP} that has compilation semantics equivalent to
 3231: @code{2dup}, but compiles @code{over over}.
 3232: @end quotation
 3233: 
 3234: @c !! @xref{Macros} for reference
 3235: 
 3236: 
 3237: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
 3238: @section @code{Literal}
 3239: @cindex literal tutorial
 3240: 
 3241: You cannot @code{POSTPONE} numbers:
 3242: 
 3243: @example
 3244: : [FOO] POSTPONE 500 ; immediate
 3245: @end example
 3246: 
 3247: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
 3248: 
 3249: @example
 3250: : [FOO] ( compilation: --; run-time: -- n )
 3251:   500 POSTPONE literal ; immediate
 3252: 
 3253: : flip [FOO] ;
 3254: flip .
 3255: see flip
 3256: @end example
 3257: 
 3258: @code{LITERAL} consumes a number at compile-time (when it's compilation
 3259: semantics are executed) and pushes it at run-time (when the code it
 3260: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
 3261: number computed at compile time into the current word:
 3262: 
 3263: @example
 3264: : bar ( -- n )
 3265:   [ 2 2 + ] literal ;
 3266: see bar
 3267: @end example
 3268: 
 3269: @quotation Assignment
 3270: Write @code{]L} which allows writing the example above as @code{: bar (
 3271: -- n ) [ 2 2 + ]L ;}
 3272: @end quotation
 3273: 
 3274: @c !! @xref{Macros} for reference
 3275: 
 3276: 
 3277: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
 3278: @section Advanced macros
 3279: @cindex macros, advanced tutorial
 3280: @cindex run-time code generation, tutorial
 3281: 
 3282: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
 3283: Execution Tokens}.  It frequently performs @code{execute}, a relatively
 3284: expensive operation in some Forth implementations.  You can use
 3285: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
 3286: and produce a word that contains the word to be performed directly:
 3287: 
 3288: @c use ]] ... [[
 3289: @example
 3290: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 3291: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 3292: \ array beginning at addr and containing u elements
 3293:   @{ xt @}
 3294:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
 3295:     POSTPONE i POSTPONE @@ xt compile,
 3296:   1 cells POSTPONE literal POSTPONE +loop ;
 3297: 
 3298: : sum-array ( addr u -- n )
 3299:  0 rot rot [ ' + compile-map-array ] ;
 3300: see sum-array
 3301: a 5 sum-array .
 3302: @end example
 3303: 
 3304: You can use the full power of Forth for generating the code; here's an
 3305: example where the code is generated in a loop:
 3306: 
 3307: @example
 3308: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
 3309: \ n2=n1+(addr1)*n, addr2=addr1+cell
 3310:   POSTPONE tuck POSTPONE @@
 3311:   POSTPONE literal POSTPONE * POSTPONE +
 3312:   POSTPONE swap POSTPONE cell+ ;
 3313: 
 3314: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
 3315: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
 3316:   0 postpone literal postpone swap
 3317:   [ ' compile-vmul-step compile-map-array ]
 3318:   postpone drop ;
 3319: see compile-vmul
 3320: 
 3321: : a-vmul ( addr -- n )
 3322: \ n=a*v, where v is a vector that's as long as a and starts at addr
 3323:  [ a 5 compile-vmul ] ;
 3324: see a-vmul
 3325: a a-vmul .
 3326: @end example
 3327: 
 3328: This example uses @code{compile-map-array} to show off, but you could
 3329: also use @code{map-array} instead (try it now!).
 3330: 
 3331: You can use this technique for efficient multiplication of large
 3332: matrices.  In matrix multiplication, you multiply every line of one
 3333: matrix with every column of the other matrix.  You can generate the code
 3334: for one line once, and use it for every column.  The only downside of
 3335: this technique is that it is cumbersome to recover the memory consumed
 3336: by the generated code when you are done (and in more complicated cases
 3337: it is not possible portably).
 3338: 
 3339: @c !! @xref{Macros} for reference
 3340: 
 3341: 
 3342: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
 3343: @section Compilation Tokens
 3344: @cindex compilation tokens, tutorial
 3345: @cindex CT, tutorial
 3346: 
 3347: This section is Gforth-specific.  You can skip it.
 3348: 
 3349: @code{' word compile,} compiles the interpretation semantics.  For words
 3350: with default compilation semantics this is the same as performing the
 3351: compilation semantics.  To represent the compilation semantics of other
 3352: words (e.g., words like @code{if} that have no interpretation
 3353: semantics), Gforth has the concept of a compilation token (CT,
 3354: consisting of two cells), and words @code{comp'} and @code{[comp']}.
 3355: You can perform the compilation semantics represented by a CT with
 3356: @code{execute}:
 3357: 
 3358: @example
 3359: : foo2 ( n1 n2 -- n )
 3360:    [ comp' + execute ] ;
 3361: see foo
 3362: @end example
 3363: 
 3364: You can compile the compilation semantics represented by a CT with
 3365: @code{postpone,}:
 3366: 
 3367: @example
 3368: : foo3 ( -- )
 3369:   [ comp' + postpone, ] ;
 3370: see foo3
 3371: @end example
 3372: 
 3373: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
 3374: @code{comp'} is particularly useful for words that have no
 3375: interpretation semantics:
 3376: 
 3377: @example
 3378: ' if
 3379: comp' if .s 2drop
 3380: @end example
 3381: 
 3382: Reference: @ref{Tokens for Words}.
 3383: 
 3384: 
 3385: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
 3386: @section Wordlists and Search Order
 3387: @cindex wordlists tutorial
 3388: @cindex search order, tutorial
 3389: 
 3390: The dictionary is not just a memory area that allows you to allocate
 3391: memory with @code{allot}, it also contains the Forth words, arranged in
 3392: several wordlists.  When searching for a word in a wordlist,
 3393: conceptually you start searching at the youngest and proceed towards
 3394: older words (in reality most systems nowadays use hash-tables); i.e., if
 3395: you define a word with the same name as an older word, the new word
 3396: shadows the older word.
 3397: 
 3398: Which wordlists are searched in which order is determined by the search
 3399: order.  You can display the search order with @code{order}.  It displays
 3400: first the search order, starting with the wordlist searched first, then
 3401: it displays the wordlist that will contain newly defined words.
 3402: 
 3403: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
 3404: 
 3405: @example
 3406: wordlist constant mywords
 3407: @end example
 3408: 
 3409: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
 3410: defined words (the @emph{current} wordlist):
 3411: 
 3412: @example
 3413: mywords set-current
 3414: order
 3415: @end example
 3416: 
 3417: Gforth does not display a name for the wordlist in @code{mywords}
 3418: because this wordlist was created anonymously with @code{wordlist}.
 3419: 
 3420: You can get the current wordlist with @code{get-current ( -- wid)}.  If
 3421: you want to put something into a specific wordlist without overall
 3422: effect on the current wordlist, this typically looks like this:
 3423: 
 3424: @example
 3425: get-current mywords set-current ( wid )
 3426: create someword
 3427: ( wid ) set-current
 3428: @end example
 3429: 
 3430: You can write the search order with @code{set-order ( wid1 .. widn n --
 3431: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
 3432: searched wordlist is topmost.
 3433: 
 3434: @example
 3435: get-order mywords swap 1+ set-order
 3436: order
 3437: @end example
 3438: 
 3439: Yes, the order of wordlists in the output of @code{order} is reversed
 3440: from stack comments and the output of @code{.s} and thus unintuitive.
 3441: 
 3442: @quotation Assignment
 3443: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
 3444: wordlist to the search order.  Define @code{previous ( -- )}, which
 3445: removes the first searched wordlist from the search order.  Experiment
 3446: with boundary conditions (you will see some crashes or situations that
 3447: are hard or impossible to leave).
 3448: @end quotation
 3449: 
 3450: The search order is a powerful foundation for providing features similar
 3451: to Modula-2 modules and C++ namespaces.  However, trying to modularize
 3452: programs in this way has disadvantages for debugging and reuse/factoring
 3453: that overcome the advantages in my experience (I don't do huge projects,
 3454: though).  These disadvantages are not so clear in other
 3455: languages/programming environments, because these languages are not so
 3456: strong in debugging and reuse.
 3457: 
 3458: @c !! example
 3459: 
 3460: Reference: @ref{Word Lists}.
 3461: 
 3462: @c ******************************************************************
 3463: @node Introduction, Words, Tutorial, Top
 3464: @comment node-name,     next,           previous, up
 3465: @chapter An Introduction to ANS Forth
 3466: @cindex Forth - an introduction
 3467: 
 3468: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
 3469: that it is slower-paced in its examples, but uses them to dive deep into
 3470: explaining Forth internals (not covered by the Tutorial).  Apart from
 3471: that, this chapter covers far less material.  It is suitable for reading
 3472: without using a computer.
 3473: 
 3474: The primary purpose of this manual is to document Gforth. However, since
 3475: Forth is not a widely-known language and there is a lack of up-to-date
 3476: teaching material, it seems worthwhile to provide some introductory
 3477: material.  For other sources of Forth-related
 3478: information, see @ref{Forth-related information}.
 3479: 
 3480: The examples in this section should work on any ANS Forth; the
 3481: output shown was produced using Gforth. Each example attempts to
 3482: reproduce the exact output that Gforth produces. If you try out the
 3483: examples (and you should), what you should type is shown @kbd{like this}
 3484: and Gforth's response is shown @code{like this}. The single exception is
 3485: that, where the example shows @key{RET} it means that you should
 3486: press the ``carriage return'' key. Unfortunately, some output formats for
 3487: this manual cannot show the difference between @kbd{this} and
 3488: @code{this} which will make trying out the examples harder (but not
 3489: impossible).
 3490: 
 3491: Forth is an unusual language. It provides an interactive development
 3492: environment which includes both an interpreter and compiler. Forth
 3493: programming style encourages you to break a problem down into many
 3494: @cindex factoring
 3495: small fragments (@dfn{factoring}), and then to develop and test each
 3496: fragment interactively. Forth advocates assert that breaking the
 3497: edit-compile-test cycle used by conventional programming languages can
 3498: lead to great productivity improvements.
 3499: 
 3500: @menu
 3501: * Introducing the Text Interpreter::  
 3502: * Stacks and Postfix notation::  
 3503: * Your first definition::       
 3504: * How does that work?::         
 3505: * Forth is written in Forth::   
 3506: * Review - elements of a Forth system::  
 3507: * Where to go next::            
 3508: * Exercises::                   
 3509: @end menu
 3510: 
 3511: @comment ----------------------------------------------
 3512: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
 3513: @section Introducing the Text Interpreter
 3514: @cindex text interpreter
 3515: @cindex outer interpreter
 3516: 
 3517: @c IMO this is too detailed and the pace is too slow for
 3518: @c an introduction.  If you know German, take a look at
 3519: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
 3520: @c to see how I do it - anton 
 3521: 
 3522: @c nac-> Where I have accepted your comments 100% and modified the text
 3523: @c accordingly, I have deleted your comments. Elsewhere I have added a
 3524: @c response like this to attempt to rationalise what I have done. Of
 3525: @c course, this is a very clumsy mechanism for something that would be
 3526: @c done far more efficiently over a beer. Please delete any dialogue
 3527: @c you consider closed.
 3528: 
 3529: When you invoke the Forth image, you will see a startup banner printed
 3530: and nothing else (if you have Gforth installed on your system, try
 3531: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
 3532: its command line interpreter, which is called the @dfn{Text Interpreter}
 3533: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
 3534: about the text interpreter as you read through this chapter, for more
 3535: detail @pxref{The Text Interpreter}).
 3536: 
 3537: Although it's not obvious, Forth is actually waiting for your
 3538: input. Type a number and press the @key{RET} key:
 3539: 
 3540: @example
 3541: @kbd{45@key{RET}}  ok
 3542: @end example
 3543: 
 3544: Rather than give you a prompt to invite you to input something, the text
 3545: interpreter prints a status message @i{after} it has processed a line
 3546: of input. The status message in this case (``@code{ ok}'' followed by
 3547: carriage-return) indicates that the text interpreter was able to process
 3548: all of your input successfully. Now type something illegal:
 3549: 
 3550: @example
 3551: @kbd{qwer341@key{RET}}
 3552: *the terminal*:2: Undefined word
 3553: >>>qwer341<<<
 3554: Backtrace:
 3555: $2A95B42A20 throw 
 3556: $2A95B57FB8 no.extensions 
 3557: @end example
 3558: 
 3559: The exact text, other than the ``Undefined word'' may differ slightly
 3560: on your system, but the effect is the same; when the text interpreter
 3561: detects an error, it discards any remaining text on a line, resets
 3562: certain internal state and prints an error message. For a detailed
 3563: description of error messages see @ref{Error messages}.
 3564: 
 3565: The text interpreter waits for you to press carriage-return, and then
 3566: processes your input line. Starting at the beginning of the line, it
 3567: breaks the line into groups of characters separated by spaces. For each
 3568: group of characters in turn, it makes two attempts to do something:
 3569: 
 3570: @itemize @bullet
 3571: @item
 3572: @cindex name dictionary
 3573: It tries to treat it as a command. It does this by searching a @dfn{name
 3574: dictionary}. If the group of characters matches an entry in the name
 3575: dictionary, the name dictionary provides the text interpreter with
 3576: information that allows the text interpreter perform some actions. In
 3577: Forth jargon, we say that the group
 3578: @cindex word
 3579: @cindex definition
 3580: @cindex execution token
 3581: @cindex xt
 3582: of characters names a @dfn{word}, that the dictionary search returns an
 3583: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
 3584: word, and that the text interpreter executes the xt. Often, the terms
 3585: @dfn{word} and @dfn{definition} are used interchangeably.
 3586: @item
 3587: If the text interpreter fails to find a match in the name dictionary, it
 3588: tries to treat the group of characters as a number in the current number
 3589: base (when you start up Forth, the current number base is base 10). If
 3590: the group of characters legitimately represents a number, the text
 3591: interpreter pushes the number onto a stack (we'll learn more about that
 3592: in the next section).
 3593: @end itemize
 3594: 
 3595: If the text interpreter is unable to do either of these things with any
 3596: group of characters, it discards the group of characters and the rest of
 3597: the line, then prints an error message. If the text interpreter reaches
 3598: the end of the line without error, it prints the status message ``@code{ ok}''
 3599: followed by carriage-return.
 3600: 
 3601: This is the simplest command we can give to the text interpreter:
 3602: 
 3603: @example
 3604: @key{RET}  ok
 3605: @end example
 3606: 
 3607: The text interpreter did everything we asked it to do (nothing) without
 3608: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
 3609: command:
 3610: 
 3611: @example
 3612: @kbd{12 dup fred dup@key{RET}}
 3613: *the terminal*:3: Undefined word
 3614: 12 dup >>>fred<<< dup
 3615: Backtrace:
 3616: $2A95B42A20 throw 
 3617: $2A95B57FB8 no.extensions 
 3618: @end example
 3619: 
 3620: When you press the carriage-return key, the text interpreter starts to
 3621: work its way along the line:
 3622: 
 3623: @itemize @bullet
 3624: @item
 3625: When it gets to the space after the @code{2}, it takes the group of
 3626: characters @code{12} and looks them up in the name
 3627: dictionary@footnote{We can't tell if it found them or not, but assume
 3628: for now that it did not}. There is no match for this group of characters
 3629: in the name dictionary, so it tries to treat them as a number. It is
 3630: able to do this successfully, so it puts the number, 12, ``on the stack''
 3631: (whatever that means).
 3632: @item
 3633: The text interpreter resumes scanning the line and gets the next group
 3634: of characters, @code{dup}. It looks it up in the name dictionary and
 3635: (you'll have to take my word for this) finds it, and executes the word
 3636: @code{dup} (whatever that means).
 3637: @item
 3638: Once again, the text interpreter resumes scanning the line and gets the
 3639: group of characters @code{fred}. It looks them up in the name
 3640: dictionary, but can't find them. It tries to treat them as a number, but
 3641: they don't represent any legal number.
 3642: @end itemize
 3643: 
 3644: At this point, the text interpreter gives up and prints an error
 3645: message. The error message shows exactly how far the text interpreter
 3646: got in processing the line. In particular, it shows that the text
 3647: interpreter made no attempt to do anything with the final character
 3648: group, @code{dup}, even though we have good reason to believe that the
 3649: text interpreter would have no problem looking that word up and
 3650: executing it a second time.
 3651: 
 3652: 
 3653: @comment ----------------------------------------------
 3654: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
 3655: @section Stacks, postfix notation and parameter passing
 3656: @cindex text interpreter
 3657: @cindex outer interpreter
 3658: 
 3659: In procedural programming languages (like C and Pascal), the
 3660: building-block of programs is the @dfn{function} or @dfn{procedure}. These
 3661: functions or procedures are called with @dfn{explicit parameters}. For
 3662: example, in C we might write:
 3663: 
 3664: @example
 3665: total = total + new_volume(length,height,depth);
 3666: @end example
 3667: 
 3668: @noindent
 3669: where new_volume is a function-call to another piece of code, and total,
 3670: length, height and depth are all variables. length, height and depth are
 3671: parameters to the function-call.
 3672: 
 3673: In Forth, the equivalent of the function or procedure is the
 3674: @dfn{definition} and parameters are implicitly passed between
 3675: definitions using a shared stack that is visible to the
 3676: programmer. Although Forth does support variables, the existence of the
 3677: stack means that they are used far less often than in most other
 3678: programming languages. When the text interpreter encounters a number, it
 3679: will place (@dfn{push}) it on the stack. There are several stacks (the
 3680: actual number is implementation-dependent ...) and the particular stack
 3681: used for any operation is implied unambiguously by the operation being
 3682: performed. The stack used for all integer operations is called the @dfn{data
 3683: stack} and, since this is the stack used most commonly, references to
 3684: ``the data stack'' are often abbreviated to ``the stack''.
 3685: 
 3686: The stacks have a last-in, first-out (LIFO) organisation. If you type:
 3687: 
 3688: @example
 3689: @kbd{1 2 3@key{RET}}  ok
 3690: @end example
 3691: 
 3692: Then this instructs the text interpreter to placed three numbers on the
 3693: (data) stack. An analogy for the behaviour of the stack is to take a
 3694: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
 3695: the table. The 3 was the last card onto the pile (``last-in'') and if
 3696: you take a card off the pile then, unless you're prepared to fiddle a
 3697: bit, the card that you take off will be the 3 (``first-out''). The
 3698: number that will be first-out of the stack is called the @dfn{top of
 3699: stack}, which
 3700: @cindex TOS definition
 3701: is often abbreviated to @dfn{TOS}.
 3702: 
 3703: To understand how parameters are passed in Forth, consider the
 3704: behaviour of the definition @code{+} (pronounced ``plus''). You will not
 3705: be surprised to learn that this definition performs addition. More
 3706: precisely, it adds two number together and produces a result. Where does
 3707: it get the two numbers from? It takes the top two numbers off the
 3708: stack. Where does it place the result? On the stack. You can act-out the
 3709: behaviour of @code{+} with your playing cards like this:
 3710: 
 3711: @itemize @bullet
 3712: @item
 3713: Pick up two cards from the stack on the table
 3714: @item
 3715: Stare at them intently and ask yourself ``what @i{is} the sum of these two
 3716: numbers''
 3717: @item
 3718: Decide that the answer is 5
 3719: @item
 3720: Shuffle the two cards back into the pack and find a 5
 3721: @item
 3722: Put a 5 on the remaining ace that's on the table.
 3723: @end itemize
 3724: 
 3725: If you don't have a pack of cards handy but you do have Forth running,
 3726: you can use the definition @code{.s} to show the current state of the stack,
 3727: without affecting the stack. Type:
 3728: 
 3729: @example
 3730: @kbd{clearstacks 1 2 3@key{RET}} ok
 3731: @kbd{.s@key{RET}} <3> 1 2 3  ok
 3732: @end example
 3733: 
 3734: The text interpreter looks up the word @code{clearstacks} and executes
 3735: it; it tidies up the stacks and removes any entries that may have been
 3736: left on it by earlier examples. The text interpreter pushes each of the
 3737: three numbers in turn onto the stack. Finally, the text interpreter
 3738: looks up the word @code{.s} and executes it. The effect of executing
 3739: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
 3740: followed by a list of all the items on the stack; the item on the far
 3741: right-hand side is the TOS.
 3742: 
 3743: You can now type:
 3744: 
 3745: @example
 3746: @kbd{+ .s@key{RET}} <2> 1 5  ok
 3747: @end example
 3748: 
 3749: @noindent
 3750: which is correct; there are now 2 items on the stack and the result of
 3751: the addition is 5.
 3752: 
 3753: If you're playing with cards, try doing a second addition: pick up the
 3754: two cards, work out that their sum is 6, shuffle them into the pack,
 3755: look for a 6 and place that on the table. You now have just one item on
 3756: the stack. What happens if you try to do a third addition? Pick up the
 3757: first card, pick up the second card -- ah! There is no second card. This
 3758: is called a @dfn{stack underflow} and consitutes an error. If you try to
 3759: do the same thing with Forth it often reports an error (probably a Stack
 3760: Underflow or an Invalid Memory Address error).
 3761: 
 3762: The opposite situation to a stack underflow is a @dfn{stack overflow},
 3763: which simply accepts that there is a finite amount of storage space
 3764: reserved for the stack. To stretch the playing card analogy, if you had
 3765: enough packs of cards and you piled the cards up on the table, you would
 3766: eventually be unable to add another card; you'd hit the ceiling. Gforth
 3767: allows you to set the maximum size of the stacks. In general, the only
 3768: time that you will get a stack overflow is because a definition has a
 3769: bug in it and is generating data on the stack uncontrollably.
 3770: 
 3771: There's one final use for the playing card analogy. If you model your
 3772: stack using a pack of playing cards, the maximum number of items on
 3773: your stack will be 52 (I assume you didn't use the Joker). The maximum
 3774: @i{value} of any item on the stack is 13 (the King). In fact, the only
 3775: possible numbers are positive integer numbers 1 through 13; you can't
 3776: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
 3777: think about some of the cards, you can accommodate different
 3778: numbers. For example, you could think of the Jack as representing 0,
 3779: the Queen as representing -1 and the King as representing -2. Your
 3780: @i{range} remains unchanged (you can still only represent a total of 13
 3781: numbers) but the numbers that you can represent are -2 through 10.
 3782: 
 3783: In that analogy, the limit was the amount of information that a single
 3784: stack entry could hold, and Forth has a similar limit. In Forth, the
 3785: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
 3786: implementation dependent and affects the maximum value that a stack
 3787: entry can hold. A Standard Forth provides a cell size of at least
 3788: 16-bits, and most desktop systems use a cell size of 32-bits.
 3789: 
 3790: Forth does not do any type checking for you, so you are free to
 3791: manipulate and combine stack items in any way you wish. A convenient way
 3792: of treating stack items is as 2's complement signed integers, and that
 3793: is what Standard words like @code{+} do. Therefore you can type:
 3794: 
 3795: @example
 3796: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
 3797: @end example
 3798: 
 3799: If you use numbers and definitions like @code{+} in order to turn Forth
 3800: into a great big pocket calculator, you will realise that it's rather
 3801: different from a normal calculator. Rather than typing 2 + 3 = you had
 3802: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
 3803: result). The terminology used to describe this difference is to say that
 3804: your calculator uses @dfn{Infix Notation} (parameters and operators are
 3805: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
 3806: operators are separate), also called @dfn{Reverse Polish Notation}.
 3807: 
 3808: Whilst postfix notation might look confusing to begin with, it has
 3809: several important advantages:
 3810: 
 3811: @itemize @bullet
 3812: @item
 3813: it is unambiguous
 3814: @item
 3815: it is more concise
 3816: @item
 3817: it fits naturally with a stack-based system
 3818: @end itemize
 3819: 
 3820: To examine these claims in more detail, consider these sums:
 3821: 
 3822: @example
 3823: 6 + 5 * 4 =
 3824: 4 * 5 + 6 =
 3825: @end example
 3826: 
 3827: If you're just learning maths or your maths is very rusty, you will
 3828: probably come up with the answer 44 for the first and 26 for the
 3829: second. If you are a bit of a whizz at maths you will remember the
 3830: @i{convention} that multiplication takes precendence over addition, and
 3831: you'd come up with the answer 26 both times. To explain the answer 26
 3832: to someone who got the answer 44, you'd probably rewrite the first sum
 3833: like this:
 3834: 
 3835: @example
 3836: 6 + (5 * 4) =
 3837: @end example
 3838: 
 3839: If what you really wanted was to perform the addition before the
 3840: multiplication, you would have to use parentheses to force it.
 3841: 
 3842: If you did the first two sums on a pocket calculator you would probably
 3843: get the right answers, unless you were very cautious and entered them using
 3844: these keystroke sequences:
 3845: 
 3846: 6 + 5 = * 4 =
 3847: 4 * 5 = + 6 =
 3848: 
 3849: Postfix notation is unambiguous because the order that the operators
 3850: are applied is always explicit; that also means that parentheses are
 3851: never required. The operators are @i{active} (the act of quoting the
 3852: operator makes the operation occur) which removes the need for ``=''.
 3853: 
 3854: The sum 6 + 5 * 4 can be written (in postfix notation) in two
 3855: equivalent ways:
 3856: 
 3857: @example
 3858: 6 5 4 * +      or:
 3859: 5 4 * 6 +
 3860: @end example
 3861: 
 3862: An important thing that you should notice about this notation is that
 3863: the @i{order} of the numbers does not change; if you want to subtract
 3864: 2 from 10 you type @code{10 2 -}.
 3865: 
 3866: The reason that Forth uses postfix notation is very simple to explain: it
 3867: makes the implementation extremely simple, and it follows naturally from
 3868: using the stack as a mechanism for passing parameters. Another way of
 3869: thinking about this is to realise that all Forth definitions are
 3870: @i{active}; they execute as they are encountered by the text
 3871: interpreter. The result of this is that the syntax of Forth is trivially
 3872: simple.
 3873: 
 3874: 
 3875: 
 3876: @comment ----------------------------------------------
 3877: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
 3878: @section Your first Forth definition
 3879: @cindex first definition
 3880: 
 3881: Until now, the examples we've seen have been trivial; we've just been
 3882: using Forth as a bigger-than-pocket calculator. Also, each calculation
 3883: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
 3884: again@footnote{That's not quite true. If you press the up-arrow key on
 3885: your keyboard you should be able to scroll back to any earlier command,
 3886: edit it and re-enter it.} In this section we'll see how to add new
 3887: words to Forth's vocabulary.
 3888: 
 3889: The easiest way to create a new word is to use a @dfn{colon
 3890: definition}. We'll define a few and try them out before worrying too
 3891: much about how they work. Try typing in these examples; be careful to
 3892: copy the spaces accurately:
 3893: 
 3894: @example
 3895: : add-two 2 + . ;
 3896: : greet ." Hello and welcome" ;
 3897: : demo 5 add-two ;
 3898: @end example
 3899: 
 3900: @noindent
 3901: Now try them out:
 3902: 
 3903: @example
 3904: @kbd{greet@key{RET}} Hello and welcome  ok
 3905: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
 3906: @kbd{4 add-two@key{RET}} 6  ok
 3907: @kbd{demo@key{RET}} 7  ok
 3908: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
 3909: @end example
 3910: 
 3911: The first new thing that we've introduced here is the pair of words
 3912: @code{:} and @code{;}. These are used to start and terminate a new
 3913: definition, respectively. The first word after the @code{:} is the name
 3914: for the new definition.
 3915: 
 3916: As you can see from the examples, a definition is built up of words that
 3917: have already been defined; Forth makes no distinction between
 3918: definitions that existed when you started the system up, and those that
 3919: you define yourself.
 3920: 
 3921: The examples also introduce the words @code{.} (dot), @code{."}
 3922: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
 3923: the stack and displays it. It's like @code{.s} except that it only
 3924: displays the top item of the stack and it is destructive; after it has
 3925: executed, the number is no longer on the stack. There is always one
 3926: space printed after the number, and no spaces before it. Dot-quote
 3927: defines a string (a sequence of characters) that will be printed when
 3928: the word is executed. The string can contain any printable characters
 3929: except @code{"}. A @code{"} has a special function; it is not a Forth
 3930: word but it acts as a delimiter (the way that delimiters work is
 3931: described in the next section). Finally, @code{dup} duplicates the value
 3932: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
 3933: 
 3934: We already know that the text interpreter searches through the
 3935: dictionary to locate names. If you've followed the examples earlier, you
 3936: will already have a definition called @code{add-two}. Lets try modifying
 3937: it by typing in a new definition:
 3938: 
 3939: @example
 3940: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
 3941: @end example
 3942: 
 3943: Forth recognised that we were defining a word that already exists, and
 3944: printed a message to warn us of that fact. Let's try out the new
 3945: definition:
 3946: 
 3947: @example
 3948: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
 3949: @end example
 3950: 
 3951: @noindent
 3952: All that we've actually done here, though, is to create a new
 3953: definition, with a particular name. The fact that there was already a
 3954: definition with the same name did not make any difference to the way
 3955: that the new definition was created (except that Forth printed a warning
 3956: message). The old definition of add-two still exists (try @code{demo}
 3957: again to see that this is true). Any new definition will use the new
 3958: definition of @code{add-two}, but old definitions continue to use the
 3959: version that already existed at the time that they were @code{compiled}.
 3960: 
 3961: Before you go on to the next section, try defining and redefining some
 3962: words of your own.
 3963: 
 3964: @comment ----------------------------------------------
 3965: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
 3966: @section How does that work?
 3967: @cindex parsing words
 3968: 
 3969: @c That's pretty deep (IMO way too deep) for an introduction. - anton
 3970: 
 3971: @c Is it a good idea to talk about the interpretation semantics of a
 3972: @c number? We don't have an xt to go along with it. - anton
 3973: 
 3974: @c Now that I have eliminated execution semantics, I wonder if it would not
 3975: @c be better to keep them (or add run-time semantics), to make it easier to
 3976: @c explain what compilation semantics usually does. - anton
 3977: 
 3978: @c nac-> I removed the term ``default compilation sematics'' from the
 3979: @c introductory chapter. Removing ``execution semantics'' was making
 3980: @c everything simpler to explain, then I think the use of this term made
 3981: @c everything more complex again. I replaced it with ``default
 3982: @c semantics'' (which is used elsewhere in the manual) by which I mean
 3983: @c ``a definition that has neither the immediate nor the compile-only
 3984: @c flag set''.
 3985: 
 3986: @c anton: I have eliminated default semantics (except in one place where it
 3987: @c means "default interpretation and compilation semantics"), because it
 3988: @c makes no sense in the presence of combined words.  I reverted to
 3989: @c "execution semantics" where necessary.
 3990: 
 3991: @c nac-> I reworded big chunks of the ``how does that work''
 3992: @c section (and, unusually for me, I think I even made it shorter!).  See
 3993: @c what you think -- I know I have not addressed your primary concern
 3994: @c that it is too heavy-going for an introduction. From what I understood
 3995: @c of your course notes it looks as though they might be a good framework. 
 3996: @c Things that I've tried to capture here are some things that came as a
 3997: @c great revelation here when I first understood them. Also, I like the
 3998: @c fact that a very simple code example shows up almost all of the issues
 3999: @c that you need to understand to see how Forth works. That's unique and
 4000: @c worthwhile to emphasise.
 4001: 
 4002: @c anton: I think it's a good idea to present the details, especially those
 4003: @c that you found to be a revelation, and probably the tutorial tries to be
 4004: @c too superficial and does not get some of the things across that make
 4005: @c Forth special.  I do believe that most of the time these things should
 4006: @c be discussed at the end of a section or in separate sections instead of
 4007: @c in the middle of a section (e.g., the stuff you added in "User-defined
 4008: @c defining words" leads in a completely different direction from the rest
 4009: @c of the section).
 4010: 
 4011: Now we're going to take another look at the definition of @code{add-two}
 4012: from the previous section. From our knowledge of the way that the text
 4013: interpreter works, we would have expected this result when we tried to
 4014: define @code{add-two}:
 4015: 
 4016: @example
 4017: @kbd{: add-two 2 + . ;@key{RET}}
 4018: *the terminal*:4: Undefined word
 4019: : >>>add-two<<< 2 + . ;
 4020: @end example
 4021: 
 4022: The reason that this didn't happen is bound up in the way that @code{:}
 4023: works. The word @code{:} does two special things. The first special
 4024: thing that it does prevents the text interpreter from ever seeing the
 4025: characters @code{add-two}. The text interpreter uses a variable called
 4026: @cindex modifying >IN
 4027: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
 4028: input line. When it encounters the word @code{:} it behaves in exactly
 4029: the same way as it does for any other word; it looks it up in the name
 4030: dictionary, finds its xt and executes it. When @code{:} executes, it
 4031: looks at the input buffer, finds the word @code{add-two} and advances the
 4032: value of @code{>IN} to point past it. It then does some other stuff
 4033: associated with creating the new definition (including creating an entry
 4034: for @code{add-two} in the name dictionary). When the execution of @code{:}
 4035: completes, control returns to the text interpreter, which is oblivious
 4036: to the fact that it has been tricked into ignoring part of the input
 4037: line.
 4038: 
 4039: @cindex parsing words
 4040: Words like @code{:} -- words that advance the value of @code{>IN} and so
 4041: prevent the text interpreter from acting on the whole of the input line
 4042: -- are called @dfn{parsing words}.
 4043: 
 4044: @cindex @code{state} - effect on the text interpreter
 4045: @cindex text interpreter - effect of state
 4046: The second special thing that @code{:} does is change the value of a
 4047: variable called @code{state}, which affects the way that the text
 4048: interpreter behaves. When Gforth starts up, @code{state} has the value
 4049: 0, and the text interpreter is said to be @dfn{interpreting}. During a
 4050: colon definition (started with @code{:}), @code{state} is set to -1 and
 4051: the text interpreter is said to be @dfn{compiling}.
 4052: 
 4053: In this example, the text interpreter is compiling when it processes the
 4054: string ``@code{2 + . ;}''. It still breaks the string down into
 4055: character sequences in the same way. However, instead of pushing the
 4056: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
 4057: into the definition of @code{add-two} that will make the number @code{2} get
 4058: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
 4059: the behaviours of @code{+} and @code{.} are also compiled into the
 4060: definition.
 4061: 
 4062: One category of words don't get compiled. These so-called @dfn{immediate
 4063: words} get executed (performed @i{now}) regardless of whether the text
 4064: interpreter is interpreting or compiling. The word @code{;} is an
 4065: immediate word. Rather than being compiled into the definition, it
 4066: executes. Its effect is to terminate the current definition, which
 4067: includes changing the value of @code{state} back to 0.
 4068: 
 4069: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
 4070: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
 4071: definition.
 4072: 
 4073: In Forth, every word or number can be described in terms of two
 4074: properties:
 4075: 
 4076: @itemize @bullet
 4077: @item
 4078: @cindex interpretation semantics
 4079: Its @dfn{interpretation semantics} describe how it will behave when the
 4080: text interpreter encounters it in @dfn{interpret} state. The
 4081: interpretation semantics of a word are represented by an @dfn{execution
 4082: token}.
 4083: @item
 4084: @cindex compilation semantics
 4085: Its @dfn{compilation semantics} describe how it will behave when the
 4086: text interpreter encounters it in @dfn{compile} state. The compilation
 4087: semantics of a word are represented in an implementation-dependent way;
 4088: Gforth uses a @dfn{compilation token}.
 4089: @end itemize
 4090: 
 4091: @noindent
 4092: Numbers are always treated in a fixed way:
 4093: 
 4094: @itemize @bullet
 4095: @item
 4096: When the number is @dfn{interpreted}, its behaviour is to push the
 4097: number onto the stack.
 4098: @item
 4099: When the number is @dfn{compiled}, a piece of code is appended to the
 4100: current definition that pushes the number when it runs. (In other words,
 4101: the compilation semantics of a number are to postpone its interpretation
 4102: semantics until the run-time of the definition that it is being compiled
 4103: into.)
 4104: @end itemize
 4105: 
 4106: Words don't behave in such a regular way, but most have @i{default
 4107: semantics} which means that they behave like this:
 4108: 
 4109: @itemize @bullet
 4110: @item
 4111: The @dfn{interpretation semantics} of the word are to do something useful.
 4112: @item
 4113: The @dfn{compilation semantics} of the word are to append its
 4114: @dfn{interpretation semantics} to the current definition (so that its
 4115: run-time behaviour is to do something useful).
 4116: @end itemize
 4117: 
 4118: @cindex immediate words
 4119: The actual behaviour of any particular word can be controlled by using
 4120: the words @code{immediate} and @code{compile-only} when the word is
 4121: defined. These words set flags in the name dictionary entry of the most
 4122: recently defined word, and these flags are retrieved by the text
 4123: interpreter when it finds the word in the name dictionary.
 4124: 
 4125: A word that is marked as @dfn{immediate} has compilation semantics that
 4126: are identical to its interpretation semantics. In other words, it
 4127: behaves like this:
 4128: 
 4129: @itemize @bullet
 4130: @item
 4131: The @dfn{interpretation semantics} of the word are to do something useful.
 4132: @item
 4133: The @dfn{compilation semantics} of the word are to do something useful
 4134: (and actually the same thing); i.e., it is executed during compilation.
 4135: @end itemize
 4136: 
 4137: Marking a word as @dfn{compile-only} prohibits the text interpreter from
 4138: performing the interpretation semantics of the word directly; an attempt
 4139: to do so will generate an error. It is never necessary to use
 4140: @code{compile-only} (and it is not even part of ANS Forth, though it is
 4141: provided by many implementations) but it is good etiquette to apply it
 4142: to a word that will not behave correctly (and might have unexpected
 4143: side-effects) in interpret state. For example, it is only legal to use
 4144: the conditional word @code{IF} within a definition. If you forget this
 4145: and try to use it elsewhere, the fact that (in Gforth) it is marked as
 4146: @code{compile-only} allows the text interpreter to generate a helpful
 4147: error message rather than subjecting you to the consequences of your
 4148: folly.
 4149: 
 4150: This example shows the difference between an immediate and a
 4151: non-immediate word:
 4152: 
 4153: @example
 4154: : show-state state @@ . ;
 4155: : show-state-now show-state ; immediate
 4156: : word1 show-state ;
 4157: : word2 show-state-now ;
 4158: @end example
 4159: 
 4160: The word @code{immediate} after the definition of @code{show-state-now}
 4161: makes that word an immediate word. These definitions introduce a new
 4162: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
 4163: variable, and leaves it on the stack. Therefore, the behaviour of
 4164: @code{show-state} is to print a number that represents the current value
 4165: of @code{state}.
 4166: 
 4167: When you execute @code{word1}, it prints the number 0, indicating that
 4168: the system is interpreting. When the text interpreter compiled the
 4169: definition of @code{word1}, it encountered @code{show-state} whose
 4170: compilation semantics are to append its interpretation semantics to the
 4171: current definition. When you execute @code{word1}, it performs the
 4172: interpretation semantics of @code{show-state}.  At the time that @code{word1}
 4173: (and therefore @code{show-state}) are executed, the system is
 4174: interpreting.
 4175: 
 4176: When you pressed @key{RET} after entering the definition of @code{word2},
 4177: you should have seen the number -1 printed, followed by ``@code{
 4178: ok}''. When the text interpreter compiled the definition of
 4179: @code{word2}, it encountered @code{show-state-now}, an immediate word,
 4180: whose compilation semantics are therefore to perform its interpretation
 4181: semantics. It is executed straight away (even before the text
 4182: interpreter has moved on to process another group of characters; the
 4183: @code{;} in this example). The effect of executing it are to display the
 4184: value of @code{state} @i{at the time that the definition of}
 4185: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
 4186: system is compiling at this time. If you execute @code{word2} it does
 4187: nothing at all.
 4188: 
 4189: @cindex @code{."}, how it works
 4190: Before leaving the subject of immediate words, consider the behaviour of
 4191: @code{."} in the definition of @code{greet}, in the previous
 4192: section. This word is both a parsing word and an immediate word. Notice
 4193: that there is a space between @code{."} and the start of the text
 4194: @code{Hello and welcome}, but that there is no space between the last
 4195: letter of @code{welcome} and the @code{"} character. The reason for this
 4196: is that @code{."} is a Forth word; it must have a space after it so that
 4197: the text interpreter can identify it. The @code{"} is not a Forth word;
 4198: it is a @dfn{delimiter}. The examples earlier show that, when the string
 4199: is displayed, there is neither a space before the @code{H} nor after the
 4200: @code{e}. Since @code{."} is an immediate word, it executes at the time
 4201: that @code{greet} is defined. When it executes, its behaviour is to
 4202: search forward in the input line looking for the delimiter. When it
 4203: finds the delimiter, it updates @code{>IN} to point past the
 4204: delimiter. It also compiles some magic code into the definition of
 4205: @code{greet}; the xt of a run-time routine that prints a text string. It
 4206: compiles the string @code{Hello and welcome} into memory so that it is
 4207: available to be printed later. When the text interpreter gains control,
 4208: the next word it finds in the input stream is @code{;} and so it
 4209: terminates the definition of @code{greet}.
 4210: 
 4211: 
 4212: @comment ----------------------------------------------
 4213: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
 4214: @section Forth is written in Forth
 4215: @cindex structure of Forth programs
 4216: 
 4217: When you start up a Forth compiler, a large number of definitions
 4218: already exist. In Forth, you develop a new application using bottom-up
 4219: programming techniques to create new definitions that are defined in
 4220: terms of existing definitions. As you create each definition you can
 4221: test and debug it interactively.
 4222: 
 4223: If you have tried out the examples in this section, you will probably
 4224: have typed them in by hand; when you leave Gforth, your definitions will
 4225: be lost. You can avoid this by using a text editor to enter Forth source
 4226: code into a file, and then loading code from the file using
 4227: @code{include} (@pxref{Forth source files}). A Forth source file is
 4228: processed by the text interpreter, just as though you had typed it in by
 4229: hand@footnote{Actually, there are some subtle differences -- see
 4230: @ref{The Text Interpreter}.}.
 4231: 
 4232: Gforth also supports the traditional Forth alternative to using text
 4233: files for program entry (@pxref{Blocks}).
 4234: 
 4235: In common with many, if not most, Forth compilers, most of Gforth is
 4236: actually written in Forth. All of the @file{.fs} files in the
 4237: installation directory@footnote{For example,
 4238: @file{/usr/local/share/gforth...}} are Forth source files, which you can
 4239: study to see examples of Forth programming.
 4240: 
 4241: Gforth maintains a history file that records every line that you type to
 4242: the text interpreter. This file is preserved between sessions, and is
 4243: used to provide a command-line recall facility. If you enter long
 4244: definitions by hand, you can use a text editor to paste them out of the
 4245: history file into a Forth source file for reuse at a later time
 4246: (for more information @pxref{Command-line editing}).
 4247: 
 4248: 
 4249: @comment ----------------------------------------------
 4250: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
 4251: @section Review - elements of a Forth system
 4252: @cindex elements of a Forth system
 4253: 
 4254: To summarise this chapter:
 4255: 
 4256: @itemize @bullet
 4257: @item
 4258: Forth programs use @dfn{factoring} to break a problem down into small
 4259: fragments called @dfn{words} or @dfn{definitions}.
 4260: @item
 4261: Forth program development is an interactive process.
 4262: @item
 4263: The main command loop that accepts input, and controls both
 4264: interpretation and compilation, is called the @dfn{text interpreter}
 4265: (also known as the @dfn{outer interpreter}).
 4266: @item
 4267: Forth has a very simple syntax, consisting of words and numbers
 4268: separated by spaces or carriage-return characters. Any additional syntax
 4269: is imposed by @dfn{parsing words}.
 4270: @item
 4271: Forth uses a stack to pass parameters between words. As a result, it
 4272: uses postfix notation.
 4273: @item
 4274: To use a word that has previously been defined, the text interpreter
 4275: searches for the word in the @dfn{name dictionary}.
 4276: @item
 4277: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
 4278: @item
 4279: The text interpreter uses the value of @code{state} to select between
 4280: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
 4281: semantics} of a word that it encounters.
 4282: @item
 4283: The relationship between the @dfn{interpretation semantics} and
 4284: @dfn{compilation semantics} for a word
 4285: depend upon the way in which the word was defined (for example, whether
 4286: it is an @dfn{immediate} word).
 4287: @item
 4288: Forth definitions can be implemented in Forth (called @dfn{high-level
 4289: definitions}) or in some other way (usually a lower-level language and
 4290: as a result often called @dfn{low-level definitions}, @dfn{code
 4291: definitions} or @dfn{primitives}).
 4292: @item
 4293: Many Forth systems are implemented mainly in Forth.
 4294: @end itemize
 4295: 
 4296: 
 4297: @comment ----------------------------------------------
 4298: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
 4299: @section Where To Go Next
 4300: @cindex where to go next
 4301: 
 4302: Amazing as it may seem, if you have read (and understood) this far, you
 4303: know almost all the fundamentals about the inner workings of a Forth
 4304: system. You certainly know enough to be able to read and understand the
 4305: rest of this manual and the ANS Forth document, to learn more about the
 4306: facilities that Forth in general and Gforth in particular provide. Even
 4307: scarier, you know almost enough to implement your own Forth system.
 4308: However, that's not a good idea just yet... better to try writing some
 4309: programs in Gforth.
 4310: 
 4311: Forth has such a rich vocabulary that it can be hard to know where to
 4312: start in learning it. This section suggests a few sets of words that are
 4313: enough to write small but useful programs. Use the word index in this
 4314: document to learn more about each word, then try it out and try to write
 4315: small definitions using it. Start by experimenting with these words:
 4316: 
 4317: @itemize @bullet
 4318: @item
 4319: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
 4320: @item
 4321: Comparison: @code{MIN MAX =}
 4322: @item
 4323: Logic: @code{AND OR XOR NOT}
 4324: @item
 4325: Stack manipulation: @code{DUP DROP SWAP OVER}
 4326: @item
 4327: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
 4328: @item
 4329: Input/Output: @code{. ." EMIT CR KEY}
 4330: @item
 4331: Defining words: @code{: ; CREATE}
 4332: @item
 4333: Memory allocation words: @code{ALLOT ,}
 4334: @item
 4335: Tools: @code{SEE WORDS .S MARKER}
 4336: @end itemize
 4337: 
 4338: When you have mastered those, go on to:
 4339: 
 4340: @itemize @bullet
 4341: @item
 4342: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
 4343: @item
 4344: Memory access: @code{@@ !}
 4345: @end itemize
 4346: 
 4347: When you have mastered these, there's nothing for it but to read through
 4348: the whole of this manual and find out what you've missed.
 4349: 
 4350: @comment ----------------------------------------------
 4351: @node Exercises,  , Where to go next, Introduction
 4352: @section Exercises
 4353: @cindex exercises
 4354: 
 4355: TODO: provide a set of programming excercises linked into the stuff done
 4356: already and into other sections of the manual. Provide solutions to all
 4357: the exercises in a .fs file in the distribution.
 4358: 
 4359: @c Get some inspiration from Starting Forth and Kelly&Spies.
 4360: 
 4361: @c excercises:
 4362: @c 1. take inches and convert to feet and inches.
 4363: @c 2. take temperature and convert from fahrenheight to celcius;
 4364: @c    may need to care about symmetric vs floored??
 4365: @c 3. take input line and do character substitution
 4366: @c    to encipher or decipher
 4367: @c 4. as above but work on a file for in and out
 4368: @c 5. take input line and convert to pig-latin 
 4369: @c
 4370: @c thing of sets of things to exercise then come up with
 4371: @c problems that need those things.
 4372: 
 4373: 
 4374: @c ******************************************************************
 4375: @node Words, Error messages, Introduction, Top
 4376: @chapter Forth Words
 4377: @cindex words
 4378: 
 4379: @menu
 4380: * Notation::                    
 4381: * Case insensitivity::          
 4382: * Comments::                    
 4383: * Boolean Flags::               
 4384: * Arithmetic::                  
 4385: * Stack Manipulation::          
 4386: * Memory::                      
 4387: * Control Structures::          
 4388: * Defining Words::              
 4389: * Interpretation and Compilation Semantics::  
 4390: * Tokens for Words::            
 4391: * Compiling words::             
 4392: * The Text Interpreter::        
 4393: * The Input Stream::            
 4394: * Word Lists::                  
 4395: * Environmental Queries::       
 4396: * Files::                       
 4397: * Blocks::                      
 4398: * Other I/O::                   
 4399: * OS command line arguments::   
 4400: * Locals::                      
 4401: * Structures::                  
 4402: * Object-oriented Forth::       
 4403: * Programming Tools::           
 4404: * C Interface::                 
 4405: * Assembler and Code Words::    
 4406: * Threading Words::             
 4407: * Passing Commands to the OS::  
 4408: * Keeping track of Time::       
 4409: * Miscellaneous Words::         
 4410: @end menu
 4411: 
 4412: @node Notation, Case insensitivity, Words, Words
 4413: @section Notation
 4414: @cindex notation of glossary entries
 4415: @cindex format of glossary entries
 4416: @cindex glossary notation format
 4417: @cindex word glossary entry format
 4418: 
 4419: The Forth words are described in this section in the glossary notation
 4420: that has become a de-facto standard for Forth texts:
 4421: 
 4422: @format
 4423: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
 4424: @end format
 4425: @i{Description}
 4426: 
 4427: @table @var
 4428: @item word
 4429: The name of the word.
 4430: 
 4431: @item Stack effect
 4432: @cindex stack effect
 4433: The stack effect is written in the notation @code{@i{before} --
 4434: @i{after}}, where @i{before} and @i{after} describe the top of
 4435: stack entries before and after the execution of the word. The rest of
 4436: the stack is not touched by the word. The top of stack is rightmost,
 4437: i.e., a stack sequence is written as it is typed in. Note that Gforth
 4438: uses a separate floating point stack, but a unified stack
 4439: notation. Also, return stack effects are not shown in @i{stack
 4440: effect}, but in @i{Description}. The name of a stack item describes
 4441: the type and/or the function of the item. See below for a discussion of
 4442: the types.
 4443: 
 4444: All words have two stack effects: A compile-time stack effect and a
 4445: run-time stack effect. The compile-time stack-effect of most words is
 4446: @i{ -- }. If the compile-time stack-effect of a word deviates from
 4447: this standard behaviour, or the word does other unusual things at
 4448: compile time, both stack effects are shown; otherwise only the run-time
 4449: stack effect is shown.
 4450: 
 4451: Also note that in code templates or examples there can be comments in
 4452: parentheses that display the stack picture at this point; there is no
 4453: @code{--} in these places, because there is no before-after situation.
 4454: 
 4455: @cindex pronounciation of words
 4456: @item pronunciation
 4457: How the word is pronounced.
 4458: 
 4459: @cindex wordset
 4460: @cindex environment wordset
 4461: @item wordset
 4462: The ANS Forth standard is divided into several word sets. A standard
 4463: system need not support all of them. Therefore, in theory, the fewer
 4464: word sets your program uses the more portable it will be. However, we
 4465: suspect that most ANS Forth systems on personal machines will feature
 4466: all word sets. Words that are not defined in ANS Forth have
 4467: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
 4468: describes words that will work in future releases of Gforth;
 4469: @code{gforth-internal} words are more volatile. Environmental query
 4470: strings are also displayed like words; you can recognize them by the
 4471: @code{environment} in the word set field.
 4472: 
 4473: @item Description
 4474: A description of the behaviour of the word.
 4475: @end table
 4476: 
 4477: @cindex types of stack items
 4478: @cindex stack item types
 4479: The type of a stack item is specified by the character(s) the name
 4480: starts with:
 4481: 
 4482: @table @code
 4483: @item f
 4484: @cindex @code{f}, stack item type
 4485: Boolean flags, i.e. @code{false} or @code{true}.
 4486: @item c
 4487: @cindex @code{c}, stack item type
 4488: Char
 4489: @item w
 4490: @cindex @code{w}, stack item type
 4491: Cell, can contain an integer or an address
 4492: @item n
 4493: @cindex @code{n}, stack item type
 4494: signed integer
 4495: @item u
 4496: @cindex @code{u}, stack item type
 4497: unsigned integer
 4498: @item d
 4499: @cindex @code{d}, stack item type
 4500: double sized signed integer
 4501: @item ud
 4502: @cindex @code{ud}, stack item type
 4503: double sized unsigned integer
 4504: @item r
 4505: @cindex @code{r}, stack item type
 4506: Float (on the FP stack)
 4507: @item a-
 4508: @cindex @code{a_}, stack item type
 4509: Cell-aligned address
 4510: @item c-
 4511: @cindex @code{c_}, stack item type
 4512: Char-aligned address (note that a Char may have two bytes in Windows NT)
 4513: @item f-
 4514: @cindex @code{f_}, stack item type
 4515: Float-aligned address
 4516: @item df-
 4517: @cindex @code{df_}, stack item type
 4518: Address aligned for IEEE double precision float
 4519: @item sf-
 4520: @cindex @code{sf_}, stack item type
 4521: Address aligned for IEEE single precision float
 4522: @item xt
 4523: @cindex @code{xt}, stack item type
 4524: Execution token, same size as Cell
 4525: @item wid
 4526: @cindex @code{wid}, stack item type
 4527: Word list ID, same size as Cell
 4528: @item ior, wior
 4529: @cindex ior type description
 4530: @cindex wior type description
 4531: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
 4532: @item f83name
 4533: @cindex @code{f83name}, stack item type
 4534: Pointer to a name structure
 4535: @item "
 4536: @cindex @code{"}, stack item type
 4537: string in the input stream (not on the stack). The terminating character
 4538: is a blank by default. If it is not a blank, it is shown in @code{<>}
 4539: quotes.
 4540: @end table
 4541: 
 4542: @comment ----------------------------------------------
 4543: @node Case insensitivity, Comments, Notation, Words
 4544: @section Case insensitivity
 4545: @cindex case sensitivity
 4546: @cindex upper and lower case
 4547: 
 4548: Gforth is case-insensitive; you can enter definitions and invoke
 4549: Standard words using upper, lower or mixed case (however,
 4550: @pxref{core-idef, Implementation-defined options, Implementation-defined
 4551: options}).
 4552: 
 4553: ANS Forth only @i{requires} implementations to recognise Standard words
 4554: when they are typed entirely in upper case. Therefore, a Standard
 4555: program must use upper case for all Standard words. You can use whatever
 4556: case you like for words that you define, but in a Standard program you
 4557: have to use the words in the same case that you defined them.
 4558: 
 4559: Gforth supports case sensitivity through @code{table}s (case-sensitive
 4560: wordlists, @pxref{Word Lists}).
 4561: 
 4562: Two people have asked how to convert Gforth to be case-sensitive; while
 4563: we think this is a bad idea, you can change all wordlists into tables
 4564: like this:
 4565: 
 4566: @example
 4567: ' table-find forth-wordlist wordlist-map @ !
 4568: @end example
 4569: 
 4570: Note that you now have to type the predefined words in the same case
 4571: that we defined them, which are varying.  You may want to convert them
 4572: to your favourite case before doing this operation (I won't explain how,
 4573: because if you are even contemplating doing this, you'd better have
 4574: enough knowledge of Forth systems to know this already).
 4575: 
 4576: @node Comments, Boolean Flags, Case insensitivity, Words
 4577: @section Comments
 4578: @cindex comments
 4579: 
 4580: Forth supports two styles of comment; the traditional @i{in-line} comment,
 4581: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
 4582: 
 4583: 
 4584: doc-(
 4585: doc-\
 4586: doc-\G
 4587: 
 4588: 
 4589: @node Boolean Flags, Arithmetic, Comments, Words
 4590: @section Boolean Flags
 4591: @cindex Boolean flags
 4592: 
 4593: A Boolean flag is cell-sized. A cell with all bits clear represents the
 4594: flag @code{false} and a flag with all bits set represents the flag
 4595: @code{true}. Words that check a flag (for example, @code{IF}) will treat
 4596: a cell that has @i{any} bit set as @code{true}.
 4597: @c on and off to Memory? 
 4598: @c true and false to "Bitwise operations" or "Numeric comparison"?
 4599: 
 4600: doc-true
 4601: doc-false
 4602: doc-on
 4603: doc-off
 4604: 
 4605: 
 4606: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
 4607: @section Arithmetic
 4608: @cindex arithmetic words
 4609: 
 4610: @cindex division with potentially negative operands
 4611: Forth arithmetic is not checked, i.e., you will not hear about integer
 4612: overflow on addition or multiplication, you may hear about division by
 4613: zero if you are lucky. The operator is written after the operands, but
 4614: the operands are still in the original order. I.e., the infix @code{2-1}
 4615: corresponds to @code{2 1 -}. Forth offers a variety of division
 4616: operators. If you perform division with potentially negative operands,
 4617: you do not want to use @code{/} or @code{/mod} with its undefined
 4618: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
 4619: former, @pxref{Mixed precision}).
 4620: @comment TODO discuss the different division forms and the std approach
 4621: 
 4622: @menu
 4623: * Single precision::            
 4624: * Double precision::            Double-cell integer arithmetic
 4625: * Bitwise operations::          
 4626: * Numeric comparison::          
 4627: * Mixed precision::             Operations with single and double-cell integers
 4628: * Floating Point::              
 4629: @end menu
 4630: 
 4631: @node Single precision, Double precision, Arithmetic, Arithmetic
 4632: @subsection Single precision
 4633: @cindex single precision arithmetic words
 4634: 
 4635: @c !! cell undefined
 4636: 
 4637: By default, numbers in Forth are single-precision integers that are one
 4638: cell in size. They can be signed or unsigned, depending upon how you
 4639: treat them. For the rules used by the text interpreter for recognising
 4640: single-precision integers see @ref{Number Conversion}.
 4641: 
 4642: These words are all defined for signed operands, but some of them also
 4643: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
 4644: @code{*}.
 4645: 
 4646: doc-+
 4647: doc-1+
 4648: doc-under+
 4649: doc--
 4650: doc-1-
 4651: doc-*
 4652: doc-/
 4653: doc-mod
 4654: doc-/mod
 4655: doc-negate
 4656: doc-abs
 4657: doc-min
 4658: doc-max
 4659: doc-floored
 4660: 
 4661: 
 4662: @node Double precision, Bitwise operations, Single precision, Arithmetic
 4663: @subsection Double precision
 4664: @cindex double precision arithmetic words
 4665: 
 4666: For the rules used by the text interpreter for
 4667: recognising double-precision integers, see @ref{Number Conversion}.
 4668: 
 4669: A double precision number is represented by a cell pair, with the most
 4670: significant cell at the TOS. It is trivial to convert an unsigned single
 4671: to a double: simply push a @code{0} onto the TOS. Since numbers are
 4672: represented by Gforth using 2's complement arithmetic, converting a
 4673: signed single to a (signed) double requires sign-extension across the
 4674: most significant cell. This can be achieved using @code{s>d}. The moral
 4675: of the story is that you cannot convert a number without knowing whether
 4676: it represents an unsigned or a signed number.
 4677: 
 4678: These words are all defined for signed operands, but some of them also
 4679: work for unsigned numbers: @code{d+}, @code{d-}.
 4680: 
 4681: doc-s>d
 4682: doc-d>s
 4683: doc-d+
 4684: doc-d-
 4685: doc-dnegate
 4686: doc-dabs
 4687: doc-dmin
 4688: doc-dmax
 4689: 
 4690: 
 4691: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
 4692: @subsection Bitwise operations
 4693: @cindex bitwise operation words
 4694: 
 4695: 
 4696: doc-and
 4697: doc-or
 4698: doc-xor
 4699: doc-invert
 4700: doc-lshift
 4701: doc-rshift
 4702: doc-2*
 4703: doc-d2*
 4704: doc-2/
 4705: doc-d2/
 4706: 
 4707: 
 4708: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
 4709: @subsection Numeric comparison
 4710: @cindex numeric comparison words
 4711: 
 4712: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
 4713: d0= d0<>}) work for for both signed and unsigned numbers.
 4714: 
 4715: doc-<
 4716: doc-<=
 4717: doc-<>
 4718: doc-=
 4719: doc->
 4720: doc->=
 4721: 
 4722: doc-0<
 4723: doc-0<=
 4724: doc-0<>
 4725: doc-0=
 4726: doc-0>
 4727: doc-0>=
 4728: 
 4729: doc-u<
 4730: doc-u<=
 4731: @c u<> and u= exist but are the same as <> and =
 4732: @c doc-u<>
 4733: @c doc-u=
 4734: doc-u>
 4735: doc-u>=
 4736: 
 4737: doc-within
 4738: 
 4739: doc-d<
 4740: doc-d<=
 4741: doc-d<>
 4742: doc-d=
 4743: doc-d>
 4744: doc-d>=
 4745: 
 4746: doc-d0<
 4747: doc-d0<=
 4748: doc-d0<>
 4749: doc-d0=
 4750: doc-d0>
 4751: doc-d0>=
 4752: 
 4753: doc-du<
 4754: doc-du<=
 4755: @c du<> and du= exist but are the same as d<> and d=
 4756: @c doc-du<>
 4757: @c doc-du=
 4758: doc-du>
 4759: doc-du>=
 4760: 
 4761: 
 4762: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
 4763: @subsection Mixed precision
 4764: @cindex mixed precision arithmetic words
 4765: 
 4766: 
 4767: doc-m+
 4768: doc-*/
 4769: doc-*/mod
 4770: doc-m*
 4771: doc-um*
 4772: doc-m*/
 4773: doc-um/mod
 4774: doc-fm/mod
 4775: doc-sm/rem
 4776: 
 4777: 
 4778: @node Floating Point,  , Mixed precision, Arithmetic
 4779: @subsection Floating Point
 4780: @cindex floating point arithmetic words
 4781: 
 4782: For the rules used by the text interpreter for
 4783: recognising floating-point numbers see @ref{Number Conversion}.
 4784: 
 4785: Gforth has a separate floating point stack, but the documentation uses
 4786: the unified notation.@footnote{It's easy to generate the separate
 4787: notation from that by just separating the floating-point numbers out:
 4788: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
 4789: r3 )}.}
 4790: 
 4791: @cindex floating-point arithmetic, pitfalls
 4792: Floating point numbers have a number of unpleasant surprises for the
 4793: unwary (e.g., floating point addition is not associative) and even a
 4794: few for the wary. You should not use them unless you know what you are
 4795: doing or you don't care that the results you get are totally bogus. If
 4796: you want to learn about the problems of floating point numbers (and
 4797: how to avoid them), you might start with @cite{David Goldberg,
 4798: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
 4799: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
 4800: Computing Surveys 23(1):5@minus{}48, March 1991}.
 4801: 
 4802: 
 4803: doc-d>f
 4804: doc-f>d
 4805: doc-f+
 4806: doc-f-
 4807: doc-f*
 4808: doc-f/
 4809: doc-fnegate
 4810: doc-fabs
 4811: doc-fmax
 4812: doc-fmin
 4813: doc-floor
 4814: doc-fround
 4815: doc-f**
 4816: doc-fsqrt
 4817: doc-fexp
 4818: doc-fexpm1
 4819: doc-fln
 4820: doc-flnp1
 4821: doc-flog
 4822: doc-falog
 4823: doc-f2*
 4824: doc-f2/
 4825: doc-1/f
 4826: doc-precision
 4827: doc-set-precision
 4828: 
 4829: @cindex angles in trigonometric operations
 4830: @cindex trigonometric operations
 4831: Angles in floating point operations are given in radians (a full circle
 4832: has 2 pi radians).
 4833: 
 4834: doc-fsin
 4835: doc-fcos
 4836: doc-fsincos
 4837: doc-ftan
 4838: doc-fasin
 4839: doc-facos
 4840: doc-fatan
 4841: doc-fatan2
 4842: doc-fsinh
 4843: doc-fcosh
 4844: doc-ftanh
 4845: doc-fasinh
 4846: doc-facosh
 4847: doc-fatanh
 4848: doc-pi
 4849: 
 4850: @cindex equality of floats
 4851: @cindex floating-point comparisons
 4852: One particular problem with floating-point arithmetic is that comparison
 4853: for equality often fails when you would expect it to succeed.  For this
 4854: reason approximate equality is often preferred (but you still have to
 4855: know what you are doing).  Also note that IEEE NaNs may compare
 4856: differently from what you might expect.  The comparison words are:
 4857: 
 4858: doc-f~rel
 4859: doc-f~abs
 4860: doc-f~
 4861: doc-f=
 4862: doc-f<>
 4863: 
 4864: doc-f<
 4865: doc-f<=
 4866: doc-f>
 4867: doc-f>=
 4868: 
 4869: doc-f0<
 4870: doc-f0<=
 4871: doc-f0<>
 4872: doc-f0=
 4873: doc-f0>
 4874: doc-f0>=
 4875: 
 4876: 
 4877: @node Stack Manipulation, Memory, Arithmetic, Words
 4878: @section Stack Manipulation
 4879: @cindex stack manipulation words
 4880: 
 4881: @cindex floating-point stack in the standard
 4882: Gforth maintains a number of separate stacks:
 4883: 
 4884: @cindex data stack
 4885: @cindex parameter stack
 4886: @itemize @bullet
 4887: @item
 4888: A data stack (also known as the @dfn{parameter stack}) -- for
 4889: characters, cells, addresses, and double cells.
 4890: 
 4891: @cindex floating-point stack
 4892: @item
 4893: A floating point stack -- for holding floating point (FP) numbers.
 4894: 
 4895: @cindex return stack
 4896: @item
 4897: A return stack -- for holding the return addresses of colon
 4898: definitions and other (non-FP) data.
 4899: 
 4900: @cindex locals stack
 4901: @item
 4902: A locals stack -- for holding local variables.
 4903: @end itemize
 4904: 
 4905: @menu
 4906: * Data stack::                  
 4907: * Floating point stack::        
 4908: * Return stack::                
 4909: * Locals stack::                
 4910: * Stack pointer manipulation::  
 4911: @end menu
 4912: 
 4913: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
 4914: @subsection Data stack
 4915: @cindex data stack manipulation words
 4916: @cindex stack manipulations words, data stack
 4917: 
 4918: 
 4919: doc-drop
 4920: doc-nip
 4921: doc-dup
 4922: doc-over
 4923: doc-tuck
 4924: doc-swap
 4925: doc-pick
 4926: doc-rot
 4927: doc--rot
 4928: doc-?dup
 4929: doc-roll
 4930: doc-2drop
 4931: doc-2nip
 4932: doc-2dup
 4933: doc-2over
 4934: doc-2tuck
 4935: doc-2swap
 4936: doc-2rot
 4937: 
 4938: 
 4939: @node Floating point stack, Return stack, Data stack, Stack Manipulation
 4940: @subsection Floating point stack
 4941: @cindex floating-point stack manipulation words
 4942: @cindex stack manipulation words, floating-point stack
 4943: 
 4944: Whilst every sane Forth has a separate floating-point stack, it is not
 4945: strictly required; an ANS Forth system could theoretically keep
 4946: floating-point numbers on the data stack. As an additional difficulty,
 4947: you don't know how many cells a floating-point number takes. It is
 4948: reportedly possible to write words in a way that they work also for a
 4949: unified stack model, but we do not recommend trying it. Instead, just
 4950: say that your program has an environmental dependency on a separate
 4951: floating-point stack.
 4952: 
 4953: doc-floating-stack
 4954: 
 4955: doc-fdrop
 4956: doc-fnip
 4957: doc-fdup
 4958: doc-fover
 4959: doc-ftuck
 4960: doc-fswap
 4961: doc-fpick
 4962: doc-frot
 4963: 
 4964: 
 4965: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
 4966: @subsection Return stack
 4967: @cindex return stack manipulation words
 4968: @cindex stack manipulation words, return stack
 4969: 
 4970: @cindex return stack and locals
 4971: @cindex locals and return stack
 4972: A Forth system is allowed to keep local variables on the
 4973: return stack. This is reasonable, as local variables usually eliminate
 4974: the need to use the return stack explicitly. So, if you want to produce
 4975: a standard compliant program and you are using local variables in a
 4976: word, forget about return stack manipulations in that word (refer to the
 4977: standard document for the exact rules).
 4978: 
 4979: doc->r
 4980: doc-r>
 4981: doc-r@
 4982: doc-rdrop
 4983: doc-2>r
 4984: doc-2r>
 4985: doc-2r@
 4986: doc-2rdrop
 4987: 
 4988: 
 4989: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
 4990: @subsection Locals stack
 4991: 
 4992: Gforth uses an extra locals stack.  It is described, along with the
 4993: reasons for its existence, in @ref{Locals implementation}.
 4994: 
 4995: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
 4996: @subsection Stack pointer manipulation
 4997: @cindex stack pointer manipulation words
 4998: 
 4999: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
 5000: doc-sp0
 5001: doc-sp@
 5002: doc-sp!
 5003: doc-fp0
 5004: doc-fp@
 5005: doc-fp!
 5006: doc-rp0
 5007: doc-rp@
 5008: doc-rp!
 5009: doc-lp0
 5010: doc-lp@
 5011: doc-lp!
 5012: 
 5013: 
 5014: @node Memory, Control Structures, Stack Manipulation, Words
 5015: @section Memory
 5016: @cindex memory words
 5017: 
 5018: @menu
 5019: * Memory model::                
 5020: * Dictionary allocation::       
 5021: * Heap Allocation::             
 5022: * Memory Access::               
 5023: * Address arithmetic::          
 5024: * Memory Blocks::               
 5025: @end menu
 5026: 
 5027: In addition to the standard Forth memory allocation words, there is also
 5028: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 5029: garbage collector}.
 5030: 
 5031: @node Memory model, Dictionary allocation, Memory, Memory
 5032: @subsection ANS Forth and Gforth memory models
 5033: 
 5034: @c The ANS Forth description is a mess (e.g., is the heap part of
 5035: @c the dictionary?), so let's not stick to closely with it.
 5036: 
 5037: ANS Forth considers a Forth system as consisting of several address
 5038: spaces, of which only @dfn{data space} is managed and accessible with
 5039: the memory words.  Memory not necessarily in data space includes the
 5040: stacks, the code (called code space) and the headers (called name
 5041: space). In Gforth everything is in data space, but the code for the
 5042: primitives is usually read-only.
 5043: 
 5044: Data space is divided into a number of areas: The (data space portion of
 5045: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
 5046: refer to the search data structure embodied in word lists and headers,
 5047: because it is used for looking up names, just as you would in a
 5048: conventional dictionary.}, the heap, and a number of system-allocated
 5049: buffers.
 5050: 
 5051: @cindex address arithmetic restrictions, ANS vs. Gforth
 5052: @cindex contiguous regions, ANS vs. Gforth
 5053: In ANS Forth data space is also divided into contiguous regions.  You
 5054: can only use address arithmetic within a contiguous region, not between
 5055: them.  Usually each allocation gives you one contiguous region, but the
 5056: dictionary allocation words have additional rules (@pxref{Dictionary
 5057: allocation}).
 5058: 
 5059: Gforth provides one big address space, and address arithmetic can be
 5060: performed between any addresses. However, in the dictionary headers or
 5061: code are interleaved with data, so almost the only contiguous data space
 5062: regions there are those described by ANS Forth as contiguous; but you
 5063: can be sure that the dictionary is allocated towards increasing
 5064: addresses even between contiguous regions.  The memory order of
 5065: allocations in the heap is platform-dependent (and possibly different
 5066: from one run to the next).
 5067: 
 5068: 
 5069: @node Dictionary allocation, Heap Allocation, Memory model, Memory
 5070: @subsection Dictionary allocation
 5071: @cindex reserving data space
 5072: @cindex data space - reserving some
 5073: 
 5074: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
 5075: you want to deallocate X, you also deallocate everything
 5076: allocated after X.
 5077: 
 5078: @cindex contiguous regions in dictionary allocation
 5079: The allocations using the words below are contiguous and grow the region
 5080: towards increasing addresses.  Other words that allocate dictionary
 5081: memory of any kind (i.e., defining words including @code{:noname}) end
 5082: the contiguous region and start a new one.
 5083: 
 5084: In ANS Forth only @code{create}d words are guaranteed to produce an
 5085: address that is the start of the following contiguous region.  In
 5086: particular, the cell allocated by @code{variable} is not guaranteed to
 5087: be contiguous with following @code{allot}ed memory.
 5088: 
 5089: You can deallocate memory by using @code{allot} with a negative argument
 5090: (with some restrictions, see @code{allot}). For larger deallocations use
 5091: @code{marker}.
 5092: 
 5093: 
 5094: doc-here
 5095: doc-unused
 5096: doc-allot
 5097: doc-c,
 5098: doc-f,
 5099: doc-,
 5100: doc-2,
 5101: 
 5102: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
 5103: course you should allocate memory in an aligned way, too. I.e., before
 5104: allocating allocating a cell, @code{here} must be cell-aligned, etc.
 5105: The words below align @code{here} if it is not already.  Basically it is
 5106: only already aligned for a type, if the last allocation was a multiple
 5107: of the size of this type and if @code{here} was aligned for this type
 5108: before.
 5109: 
 5110: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
 5111: ANS Forth (@code{maxalign}ed in Gforth).
 5112: 
 5113: doc-align
 5114: doc-falign
 5115: doc-sfalign
 5116: doc-dfalign
 5117: doc-maxalign
 5118: doc-cfalign
 5119: 
 5120: 
 5121: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
 5122: @subsection Heap allocation
 5123: @cindex heap allocation
 5124: @cindex dynamic allocation of memory
 5125: @cindex memory-allocation word set
 5126: 
 5127: @cindex contiguous regions and heap allocation
 5128: Heap allocation supports deallocation of allocated memory in any
 5129: order. Dictionary allocation is not affected by it (i.e., it does not
 5130: end a contiguous region). In Gforth, these words are implemented using
 5131: the standard C library calls malloc(), free() and resize().
 5132: 
 5133: The memory region produced by one invocation of @code{allocate} or
 5134: @code{resize} is internally contiguous.  There is no contiguity between
 5135: such a region and any other region (including others allocated from the
 5136: heap).
 5137: 
 5138: doc-allocate
 5139: doc-free
 5140: doc-resize
 5141: 
 5142: 
 5143: @node Memory Access, Address arithmetic, Heap Allocation, Memory
 5144: @subsection Memory Access
 5145: @cindex memory access words
 5146: 
 5147: doc-@
 5148: doc-!
 5149: doc-+!
 5150: doc-c@
 5151: doc-c!
 5152: doc-2@
 5153: doc-2!
 5154: doc-f@
 5155: doc-f!
 5156: doc-sf@
 5157: doc-sf!
 5158: doc-df@
 5159: doc-df!
 5160: doc-sw@
 5161: doc-uw@
 5162: doc-w!
 5163: doc-sl@
 5164: doc-ul@
 5165: doc-l!
 5166: 
 5167: @node Address arithmetic, Memory Blocks, Memory Access, Memory
 5168: @subsection Address arithmetic
 5169: @cindex address arithmetic words
 5170: 
 5171: Address arithmetic is the foundation on which you can build data
 5172: structures like arrays, records (@pxref{Structures}) and objects
 5173: (@pxref{Object-oriented Forth}).
 5174: 
 5175: @cindex address unit
 5176: @cindex au (address unit)
 5177: ANS Forth does not specify the sizes of the data types. Instead, it
 5178: offers a number of words for computing sizes and doing address
 5179: arithmetic. Address arithmetic is performed in terms of address units
 5180: (aus); on most systems the address unit is one byte. Note that a
 5181: character may have more than one au, so @code{chars} is no noop (on
 5182: platforms where it is a noop, it compiles to nothing).
 5183: 
 5184: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
 5185: you have the address of a cell, perform @code{1 cells +}, and you will
 5186: have the address of the next cell.
 5187: 
 5188: @cindex contiguous regions and address arithmetic
 5189: In ANS Forth you can perform address arithmetic only within a contiguous
 5190: region, i.e., if you have an address into one region, you can only add
 5191: and subtract such that the result is still within the region; you can
 5192: only subtract or compare addresses from within the same contiguous
 5193: region.  Reasons: several contiguous regions can be arranged in memory
 5194: in any way; on segmented systems addresses may have unusual
 5195: representations, such that address arithmetic only works within a
 5196: region.  Gforth provides a few more guarantees (linear address space,
 5197: dictionary grows upwards), but in general I have found it easy to stay
 5198: within contiguous regions (exception: computing and comparing to the
 5199: address just beyond the end of an array).
 5200: 
 5201: @cindex alignment of addresses for types
 5202: ANS Forth also defines words for aligning addresses for specific
 5203: types. Many computers require that accesses to specific data types
 5204: must only occur at specific addresses; e.g., that cells may only be
 5205: accessed at addresses divisible by 4. Even if a machine allows unaligned
 5206: accesses, it can usually perform aligned accesses faster. 
 5207: 
 5208: For the performance-conscious: alignment operations are usually only
 5209: necessary during the definition of a data structure, not during the
 5210: (more frequent) accesses to it.
 5211: 
 5212: ANS Forth defines no words for character-aligning addresses. This is not
 5213: an oversight, but reflects the fact that addresses that are not
 5214: char-aligned have no use in the standard and therefore will not be
 5215: created.
 5216: 
 5217: @cindex @code{CREATE} and alignment
 5218: ANS Forth guarantees that addresses returned by @code{CREATE}d words
 5219: are cell-aligned; in addition, Gforth guarantees that these addresses
 5220: are aligned for all purposes.
 5221: 
 5222: Note that the ANS Forth word @code{char} has nothing to do with address
 5223: arithmetic.
 5224: 
 5225: 
 5226: doc-chars
 5227: doc-char+
 5228: doc-cells
 5229: doc-cell+
 5230: doc-cell
 5231: doc-aligned
 5232: doc-floats
 5233: doc-float+
 5234: doc-float
 5235: doc-faligned
 5236: doc-sfloats
 5237: doc-sfloat+
 5238: doc-sfaligned
 5239: doc-dfloats
 5240: doc-dfloat+
 5241: doc-dfaligned
 5242: doc-maxaligned
 5243: doc-cfaligned
 5244: doc-address-unit-bits
 5245: doc-/w
 5246: doc-/l
 5247: 
 5248: @node Memory Blocks,  , Address arithmetic, Memory
 5249: @subsection Memory Blocks
 5250: @cindex memory block words
 5251: @cindex character strings - moving and copying
 5252: 
 5253: Memory blocks often represent character strings; For ways of storing
 5254: character strings in memory see @ref{String Formats}.  For other
 5255: string-processing words see @ref{Displaying characters and strings}.
 5256: 
 5257: A few of these words work on address unit blocks.  In that case, you
 5258: usually have to insert @code{CHARS} before the word when working on
 5259: character strings.  Most words work on character blocks, and expect a
 5260: char-aligned address.
 5261: 
 5262: When copying characters between overlapping memory regions, use
 5263: @code{chars move} or choose carefully between @code{cmove} and
 5264: @code{cmove>}.
 5265: 
 5266: doc-move
 5267: doc-erase
 5268: doc-cmove
 5269: doc-cmove>
 5270: doc-fill
 5271: doc-blank
 5272: doc-compare
 5273: doc-str=
 5274: doc-str<
 5275: doc-string-prefix?
 5276: doc-search
 5277: doc--trailing
 5278: doc-/string
 5279: doc-bounds
 5280: doc-pad
 5281: 
 5282: @comment TODO examples
 5283: 
 5284: 
 5285: @node Control Structures, Defining Words, Memory, Words
 5286: @section Control Structures
 5287: @cindex control structures
 5288: 
 5289: Control structures in Forth cannot be used interpretively, only in a
 5290: colon definition@footnote{To be precise, they have no interpretation
 5291: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
 5292: not like this limitation, but have not seen a satisfying way around it
 5293: yet, although many schemes have been proposed.
 5294: 
 5295: @menu
 5296: * Selection::                   IF ... ELSE ... ENDIF
 5297: * Simple Loops::                BEGIN ...
 5298: * Counted Loops::               DO
 5299: * Arbitrary control structures::  
 5300: * Calls and returns::           
 5301: * Exception Handling::          
 5302: @end menu
 5303: 
 5304: @node Selection, Simple Loops, Control Structures, Control Structures
 5305: @subsection Selection
 5306: @cindex selection control structures
 5307: @cindex control structures for selection
 5308: 
 5309: @cindex @code{IF} control structure
 5310: @example
 5311: @i{flag}
 5312: IF
 5313:   @i{code}
 5314: ENDIF
 5315: @end example
 5316: @noindent
 5317: 
 5318: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
 5319: with any bit set represents truth) @i{code} is executed.
 5320: 
 5321: @example
 5322: @i{flag}
 5323: IF
 5324:   @i{code1}
 5325: ELSE
 5326:   @i{code2}
 5327: ENDIF
 5328: @end example
 5329: 
 5330: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
 5331: executed.
 5332: 
 5333: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
 5334: standard, and @code{ENDIF} is not, although it is quite popular. We
 5335: recommend using @code{ENDIF}, because it is less confusing for people
 5336: who also know other languages (and is not prone to reinforcing negative
 5337: prejudices against Forth in these people). Adding @code{ENDIF} to a
 5338: system that only supplies @code{THEN} is simple:
 5339: @example
 5340: : ENDIF   POSTPONE then ; immediate
 5341: @end example
 5342: 
 5343: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
 5344: (adv.)}  has the following meanings:
 5345: @quotation
 5346: ... 2b: following next after in order ... 3d: as a necessary consequence
 5347: (if you were there, then you saw them).
 5348: @end quotation
 5349: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
 5350: and many other programming languages has the meaning 3d.]
 5351: 
 5352: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
 5353: you can avoid using @code{?dup}. Using these alternatives is also more
 5354: efficient than using @code{?dup}. Definitions in ANS Forth
 5355: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
 5356: @file{compat/control.fs}.
 5357: 
 5358: @cindex @code{CASE} control structure
 5359: @example
 5360: @i{x}
 5361: CASE
 5362:   @i{x1} OF @i{code1} ENDOF
 5363:   @i{x2} OF @i{code2} ENDOF
 5364:   @dots{}
 5365:   ( x ) @i{default-code} ( x )
 5366: ENDCASE ( )
 5367: @end example
 5368: 
 5369: Executes the first @i{codei}, where the @i{xi} is equal to @i{x}.  If no
 5370: @i{xi} matches, the optional @i{default-code} is executed. The optional
 5371: default case can be added by simply writing the code after the last
 5372: @code{ENDOF}. It may use @i{x}, which is on top of the stack, but must
 5373: not consume it.  The value @i{x} is consumed by this construction
 5374: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
 5375: matches).  Example:
 5376: 
 5377: @example
 5378: : num-name ( n -- c-addr u )
 5379:  case
 5380:    0 of s" zero " endof
 5381:    1 of s" one "  endof
 5382:    2 of s" two "  endof
 5383:    \ default case:
 5384:    s" other number" 
 5385:    rot \ get n on top so ENDCASE can drop it
 5386:  endcase ;
 5387: @end example
 5388: 
 5389: You can also use (the non-standard) @code{?of} to use @code{case} as a
 5390: general selection structure for more than two alternatives.
 5391: @code{?Of} takes a flag.  Example:
 5392: 
 5393: @example
 5394: : sgn ( n1 -- n2 )
 5395:     \ sign function
 5396:     case
 5397: 	dup 0< ?of drop -1 endof
 5398: 	dup 0> ?of drop 1 endof
 5399: 	dup \ n1=0 -> n2=0; dup an item, to be consumed by ENDCASE
 5400:     endcase ;
 5401: @end example
 5402: 
 5403: @progstyle
 5404: To keep the code understandable, you should ensure that you change the
 5405: stack in the same way (wrt. number and types of stack items consumed
 5406: and pushed) on all paths through a selection structure.
 5407: 
 5408: @node Simple Loops, Counted Loops, Selection, Control Structures
 5409: @subsection Simple Loops
 5410: @cindex simple loops
 5411: @cindex loops without count 
 5412: 
 5413: @cindex @code{WHILE} loop
 5414: @example
 5415: BEGIN
 5416:   @i{code1}
 5417:   @i{flag}
 5418: WHILE
 5419:   @i{code2}
 5420: REPEAT
 5421: @end example
 5422: 
 5423: @i{code1} is executed and @i{flag} is computed. If it is true,
 5424: @i{code2} is executed and the loop is restarted; If @i{flag} is
 5425: false, execution continues after the @code{REPEAT}.
 5426: 
 5427: @cindex @code{UNTIL} loop
 5428: @example
 5429: BEGIN
 5430:   @i{code}
 5431:   @i{flag}
 5432: UNTIL
 5433: @end example
 5434: 
 5435: @i{code} is executed. The loop is restarted if @code{flag} is false.
 5436: 
 5437: @progstyle
 5438: To keep the code understandable, a complete iteration of the loop should
 5439: not change the number and types of the items on the stacks.
 5440: 
 5441: @cindex endless loop
 5442: @cindex loops, endless
 5443: @example
 5444: BEGIN
 5445:   @i{code}
 5446: AGAIN
 5447: @end example
 5448: 
 5449: This is an endless loop.
 5450: 
 5451: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
 5452: @subsection Counted Loops
 5453: @cindex counted loops
 5454: @cindex loops, counted
 5455: @cindex @code{DO} loops
 5456: 
 5457: The basic counted loop is:
 5458: @example
 5459: @i{limit} @i{start}
 5460: ?DO
 5461:   @i{body}
 5462: LOOP
 5463: @end example
 5464: 
 5465: This performs one iteration for every integer, starting from @i{start}
 5466: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
 5467: accessed with @code{i}. For example, the loop:
 5468: @example
 5469: 10 0 ?DO
 5470:   i .
 5471: LOOP
 5472: @end example
 5473: @noindent
 5474: prints @code{0 1 2 3 4 5 6 7 8 9}
 5475: 
 5476: The index of the innermost loop can be accessed with @code{i}, the index
 5477: of the next loop with @code{j}, and the index of the third loop with
 5478: @code{k}.
 5479: 
 5480: 
 5481: doc-i
 5482: doc-j
 5483: doc-k
 5484: 
 5485: 
 5486: The loop control data are kept on the return stack, so there are some
 5487: restrictions on mixing return stack accesses and counted loop words. In
 5488: particuler, if you put values on the return stack outside the loop, you
 5489: cannot read them inside the loop@footnote{well, not in a way that is
 5490: portable.}. If you put values on the return stack within a loop, you
 5491: have to remove them before the end of the loop and before accessing the
 5492: index of the loop.
 5493: 
 5494: There are several variations on the counted loop:
 5495: 
 5496: @itemize @bullet
 5497: @item
 5498: @code{LEAVE} leaves the innermost counted loop immediately; execution
 5499: continues after the associated @code{LOOP} or @code{NEXT}. For example:
 5500: 
 5501: @example
 5502: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
 5503: @end example
 5504: prints @code{0 1 2 3}
 5505: 
 5506: 
 5507: @item
 5508: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
 5509: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
 5510: return stack so @code{EXIT} can get to its return address. For example:
 5511: 
 5512: @example
 5513: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
 5514: @end example
 5515: prints @code{0 1 2 3}
 5516: 
 5517: 
 5518: @item
 5519: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
 5520: (and @code{LOOP} iterates until they become equal by wrap-around
 5521: arithmetic). This behaviour is usually not what you want. Therefore,
 5522: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
 5523: @code{?DO}), which do not enter the loop if @i{start} is greater than
 5524: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
 5525: unsigned loop parameters.
 5526: 
 5527: @item
 5528: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
 5529: the loop, independent of the loop parameters. Do not use @code{DO}, even
 5530: if you know that the loop is entered in any case. Such knowledge tends
 5531: to become invalid during maintenance of a program, and then the
 5532: @code{DO} will make trouble.
 5533: 
 5534: @item
 5535: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
 5536: index by @i{n} instead of by 1. The loop is terminated when the border
 5537: between @i{limit-1} and @i{limit} is crossed. E.g.:
 5538: 
 5539: @example
 5540: 4 0 +DO  i .  2 +LOOP
 5541: @end example
 5542: @noindent
 5543: prints @code{0 2}
 5544: 
 5545: @example
 5546: 4 1 +DO  i .  2 +LOOP
 5547: @end example
 5548: @noindent
 5549: prints @code{1 3}
 5550: 
 5551: @item
 5552: @cindex negative increment for counted loops
 5553: @cindex counted loops with negative increment
 5554: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
 5555: 
 5556: @example
 5557: -1 0 ?DO  i .  -1 +LOOP
 5558: @end example
 5559: @noindent
 5560: prints @code{0 -1}
 5561: 
 5562: @example
 5563: 0 0 ?DO  i .  -1 +LOOP
 5564: @end example
 5565: prints nothing.
 5566: 
 5567: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
 5568: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
 5569: index by @i{u} each iteration. The loop is terminated when the border
 5570: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
 5571: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
 5572: 
 5573: @example
 5574: -2 0 -DO  i .  1 -LOOP
 5575: @end example
 5576: @noindent
 5577: prints @code{0 -1}
 5578: 
 5579: @example
 5580: -1 0 -DO  i .  1 -LOOP
 5581: @end example
 5582: @noindent
 5583: prints @code{0}
 5584: 
 5585: @example
 5586: 0 0 -DO  i .  1 -LOOP
 5587: @end example
 5588: @noindent
 5589: prints nothing.
 5590: 
 5591: @end itemize
 5592: 
 5593: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
 5594: @code{-LOOP} are not defined in ANS Forth. However, an implementation
 5595: for these words that uses only standard words is provided in
 5596: @file{compat/loops.fs}.
 5597: 
 5598: 
 5599: @cindex @code{FOR} loops
 5600: Another counted loop is:
 5601: @example
 5602: @i{n}
 5603: FOR
 5604:   @i{body}
 5605: NEXT
 5606: @end example
 5607: This is the preferred loop of native code compiler writers who are too
 5608: lazy to optimize @code{?DO} loops properly. This loop structure is not
 5609: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
 5610: @code{i} produces values starting with @i{n} and ending with 0. Other
 5611: Forth systems may behave differently, even if they support @code{FOR}
 5612: loops. To avoid problems, don't use @code{FOR} loops.
 5613: 
 5614: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
 5615: @subsection Arbitrary control structures
 5616: @cindex control structures, user-defined
 5617: 
 5618: @cindex control-flow stack
 5619: ANS Forth permits and supports using control structures in a non-nested
 5620: way. Information about incomplete control structures is stored on the
 5621: control-flow stack. This stack may be implemented on the Forth data
 5622: stack, and this is what we have done in Gforth.
 5623: 
 5624: @cindex @code{orig}, control-flow stack item
 5625: @cindex @code{dest}, control-flow stack item
 5626: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
 5627: entry represents a backward branch target. A few words are the basis for
 5628: building any control structure possible (except control structures that
 5629: need storage, like calls, coroutines, and backtracking).
 5630: 
 5631: 
 5632: doc-if
 5633: doc-ahead
 5634: doc-then
 5635: doc-begin
 5636: doc-until
 5637: doc-again
 5638: doc-cs-pick
 5639: doc-cs-roll
 5640: 
 5641: 
 5642: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
 5643: manipulate the control-flow stack in a portable way. Without them, you
 5644: would need to know how many stack items are occupied by a control-flow
 5645: entry (many systems use one cell. In Gforth they currently take three,
 5646: but this may change in the future).
 5647: 
 5648: Some standard control structure words are built from these words:
 5649: 
 5650: 
 5651: doc-else
 5652: doc-while
 5653: doc-repeat
 5654: 
 5655: 
 5656: @noindent
 5657: Gforth adds some more control-structure words:
 5658: 
 5659: 
 5660: doc-endif
 5661: doc-?dup-if
 5662: doc-?dup-0=-if
 5663: 
 5664: 
 5665: @noindent
 5666: Counted loop words constitute a separate group of words:
 5667: 
 5668: 
 5669: doc-?do
 5670: doc-+do
 5671: doc-u+do
 5672: doc--do
 5673: doc-u-do
 5674: doc-do
 5675: doc-for
 5676: doc-loop
 5677: doc-+loop
 5678: doc--loop
 5679: doc-next
 5680: doc-leave
 5681: doc-?leave
 5682: doc-unloop
 5683: doc-done
 5684: 
 5685: 
 5686: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
 5687: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
 5688: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
 5689: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
 5690: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
 5691: resolved (by using one of the loop-ending words or @code{DONE}).
 5692: 
 5693: @noindent
 5694: Another group of control structure words are:
 5695: 
 5696: 
 5697: doc-case
 5698: doc-endcase
 5699: doc-of
 5700: doc-?ofx
 5701: doc-endof
 5702: 
 5703: 
 5704: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
 5705: @code{CS-ROLL}.
 5706: 
 5707: @subsubsection Programming Style
 5708: @cindex control structures programming style
 5709: @cindex programming style, arbitrary control structures
 5710: 
 5711: In order to ensure readability we recommend that you do not create
 5712: arbitrary control structures directly, but define new control structure
 5713: words for the control structure you want and use these words in your
 5714: program. For example, instead of writing:
 5715: 
 5716: @example
 5717: BEGIN
 5718:   ...
 5719: IF [ 1 CS-ROLL ]
 5720:   ...
 5721: AGAIN THEN
 5722: @end example
 5723: 
 5724: @noindent
 5725: we recommend defining control structure words, e.g.,
 5726: 
 5727: @example
 5728: : WHILE ( DEST -- ORIG DEST )
 5729:  POSTPONE IF
 5730:  1 CS-ROLL ; immediate
 5731: 
 5732: : REPEAT ( orig dest -- )
 5733:  POSTPONE AGAIN
 5734:  POSTPONE THEN ; immediate
 5735: @end example
 5736: 
 5737: @noindent
 5738: and then using these to create the control structure:
 5739: 
 5740: @example
 5741: BEGIN
 5742:   ...
 5743: WHILE
 5744:   ...
 5745: REPEAT
 5746: @end example
 5747: 
 5748: That's much easier to read, isn't it? Of course, @code{REPEAT} and
 5749: @code{WHILE} are predefined, so in this example it would not be
 5750: necessary to define them.
 5751: 
 5752: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
 5753: @subsection Calls and returns
 5754: @cindex calling a definition
 5755: @cindex returning from a definition
 5756: 
 5757: @cindex recursive definitions
 5758: A definition can be called simply be writing the name of the definition
 5759: to be called. Normally a definition is invisible during its own
 5760: definition. If you want to write a directly recursive definition, you
 5761: can use @code{recursive} to make the current definition visible, or
 5762: @code{recurse} to call the current definition directly.
 5763: 
 5764: 
 5765: doc-recursive
 5766: doc-recurse
 5767: 
 5768: 
 5769: @comment TODO add example of the two recursion methods
 5770: @quotation
 5771: @progstyle
 5772: I prefer using @code{recursive} to @code{recurse}, because calling the
 5773: definition by name is more descriptive (if the name is well-chosen) than
 5774: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
 5775: implementation, it is much better to read (and think) ``now sort the
 5776: partitions'' than to read ``now do a recursive call''.
 5777: @end quotation
 5778: 
 5779: For mutual recursion, use @code{Defer}red words, like this:
 5780: 
 5781: @example
 5782: Defer foo
 5783: 
 5784: : bar ( ... -- ... )
 5785:  ... foo ... ;
 5786: 
 5787: :noname ( ... -- ... )
 5788:  ... bar ... ;
 5789: IS foo
 5790: @end example
 5791: 
 5792: Deferred words are discussed in more detail in @ref{Deferred Words}.
 5793: 
 5794: The current definition returns control to the calling definition when
 5795: the end of the definition is reached or @code{EXIT} is encountered.
 5796: 
 5797: doc-exit
 5798: doc-;s
 5799: 
 5800: 
 5801: @node Exception Handling,  , Calls and returns, Control Structures
 5802: @subsection Exception Handling
 5803: @cindex exceptions
 5804: 
 5805: @c quit is a very bad idea for error handling, 
 5806: @c because it does not translate into a THROW
 5807: @c it also does not belong into this chapter
 5808: 
 5809: If a word detects an error condition that it cannot handle, it can
 5810: @code{throw} an exception.  In the simplest case, this will terminate
 5811: your program, and report an appropriate error.
 5812: 
 5813: doc-throw
 5814: 
 5815: @code{Throw} consumes a cell-sized error number on the stack. There are
 5816: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
 5817: Gforth (and most other systems) you can use the iors produced by various
 5818: words as error numbers (e.g., a typical use of @code{allocate} is
 5819: @code{allocate throw}).  Gforth also provides the word @code{exception}
 5820: to define your own error numbers (with decent error reporting); an ANS
 5821: Forth version of this word (but without the error messages) is available
 5822: in @code{compat/except.fs}.  And finally, you can use your own error
 5823: numbers (anything outside the range -4095..0), but won't get nice error
 5824: messages, only numbers.  For example, try:
 5825: 
 5826: @example
 5827: -10 throw                    \ ANS defined
 5828: -267 throw                   \ system defined
 5829: s" my error" exception throw \ user defined
 5830: 7 throw                      \ arbitrary number
 5831: @end example
 5832: 
 5833: doc---exception-exception
 5834: 
 5835: A common idiom to @code{THROW} a specific error if a flag is true is
 5836: this:
 5837: 
 5838: @example
 5839: @code{( flag ) 0<> @i{errno} and throw}
 5840: @end example
 5841: 
 5842: Your program can provide exception handlers to catch exceptions.  An
 5843: exception handler can be used to correct the problem, or to clean up
 5844: some data structures and just throw the exception to the next exception
 5845: handler.  Note that @code{throw} jumps to the dynamically innermost
 5846: exception handler.  The system's exception handler is outermost, and just
 5847: prints an error and restarts command-line interpretation (or, in batch
 5848: mode (i.e., while processing the shell command line), leaves Gforth).
 5849: 
 5850: The ANS Forth way to catch exceptions is @code{catch}:
 5851: 
 5852: doc-catch
 5853: doc-nothrow
 5854: 
 5855: The most common use of exception handlers is to clean up the state when
 5856: an error happens.  E.g.,
 5857: 
 5858: @example
 5859: base @ >r hex \ actually the hex should be inside foo, or we h
 5860: ['] foo catch ( nerror|0 )
 5861: r> base !
 5862: ( nerror|0 ) throw \ pass it on
 5863: @end example
 5864: 
 5865: A use of @code{catch} for handling the error @code{myerror} might look
 5866: like this:
 5867: 
 5868: @example
 5869: ['] foo catch
 5870: CASE
 5871:   myerror OF ... ( do something about it ) nothrow ENDOF
 5872:   dup throw \ default: pass other errors on, do nothing on non-errors
 5873: ENDCASE
 5874: @end example
 5875: 
 5876: Having to wrap the code into a separate word is often cumbersome,
 5877: therefore Gforth provides an alternative syntax:
 5878: 
 5879: @example
 5880: TRY
 5881:   @i{code1}
 5882:   IFERROR
 5883:     @i{code2}
 5884:   THEN
 5885:   @i{code3}
 5886: ENDTRY
 5887: @end example
 5888: 
 5889: This performs @i{code1}.  If @i{code1} completes normally, execution
 5890: continues with @i{code3}.  If there is an exception in @i{code1} or
 5891: before @code{endtry}, the stacks are reset to the depth during
 5892: @code{try}, the throw value is pushed on the data stack, and execution
 5893: continues at @i{code2}, and finally falls through to @i{code3}.
 5894: 
 5895: doc-try
 5896: doc-endtry
 5897: doc-iferror
 5898: 
 5899: If you don't need @i{code2}, you can write @code{restore} instead of
 5900: @code{iferror then}:
 5901: 
 5902: @example
 5903: TRY
 5904:   @i{code1}
 5905: RESTORE
 5906:   @i{code3}
 5907: ENDTRY
 5908: @end example
 5909: 
 5910: @cindex unwind-protect
 5911: The cleanup example from above in this syntax:
 5912: 
 5913: @example
 5914: base @@ @{ oldbase @}
 5915: TRY
 5916:   hex foo \ now the hex is placed correctly
 5917:   0       \ value for throw
 5918: RESTORE
 5919:   oldbase base !
 5920: ENDTRY
 5921: throw
 5922: @end example
 5923: 
 5924: An additional advantage of this variant is that an exception between
 5925: @code{restore} and @code{endtry} (e.g., from the user pressing
 5926: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
 5927: so the base will be restored under all circumstances.
 5928: 
 5929: However, you have to ensure that this code does not cause an exception
 5930: itself, otherwise the @code{iferror}/@code{restore} code will loop.
 5931: Moreover, you should also make sure that the stack contents needed by
 5932: the @code{iferror}/@code{restore} code exist everywhere between
 5933: @code{try} and @code{endtry}; in our example this is achived by
 5934: putting the data in a local before the @code{try} (you cannot use the
 5935: return stack because the exception frame (@i{sys1}) is in the way
 5936: there).
 5937: 
 5938: This kind of usage corresponds to Lisp's @code{unwind-protect}.
 5939: 
 5940: @cindex @code{recover} (old Gforth versions)
 5941: If you do not want this exception-restarting behaviour, you achieve
 5942: this as follows:
 5943: 
 5944: @example
 5945: TRY
 5946:   @i{code1}
 5947: ENDTRY-IFERROR
 5948:   @i{code2}
 5949: THEN
 5950: @end example
 5951: 
 5952: If there is an exception in @i{code1}, then @i{code2} is executed,
 5953: otherwise execution continues behind the @code{then} (or in a possible
 5954: @code{else} branch).  This corresponds to the construct
 5955: 
 5956: @example
 5957: TRY
 5958:   @i{code1}
 5959: RECOVER
 5960:   @i{code2}
 5961: ENDTRY
 5962: @end example
 5963: 
 5964: in Gforth before version 0.7.  So you can directly replace
 5965: @code{recover}-using code; however, we recommend that you check if it
 5966: would not be better to use one of the other @code{try} variants while
 5967: you are at it.
 5968: 
 5969: To ease the transition, Gforth provides two compatibility files:
 5970: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
 5971: ... then} syntax (but not @code{iferror} or @code{restore}) for old
 5972: systems; @file{recover-endtry.fs} provides the @code{try ... recover
 5973: ... endtry} syntax on new systems, so you can use that file as a
 5974: stopgap to run old programs.  Both files work on any system (they just
 5975: do nothing if the system already has the syntax it implements), so you
 5976: can unconditionally @code{require} one of these files, even if you use
 5977: a mix old and new systems.
 5978: 
 5979: doc-restore
 5980: doc-endtry-iferror
 5981: 
 5982: Here's the error handling example:
 5983: 
 5984: @example
 5985: TRY
 5986:   foo
 5987: ENDTRY-IFERROR
 5988:   CASE
 5989:     myerror OF ... ( do something about it ) nothrow ENDOF
 5990:     throw \ pass other errors on
 5991:   ENDCASE
 5992: THEN
 5993: @end example
 5994: 
 5995: @progstyle
 5996: As usual, you should ensure that the stack depth is statically known at
 5997: the end: either after the @code{throw} for passing on errors, or after
 5998: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
 5999: selection construct for handling the error).
 6000: 
 6001: There are two alternatives to @code{throw}: @code{Abort"} is conditional
 6002: and you can provide an error message.  @code{Abort} just produces an
 6003: ``Aborted'' error.
 6004: 
 6005: The problem with these words is that exception handlers cannot
 6006: differentiate between different @code{abort"}s; they just look like
 6007: @code{-2 throw} to them (the error message cannot be accessed by
 6008: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
 6009: exception handlers.
 6010: 
 6011: doc-abort"
 6012: doc-abort
 6013: 
 6014: 
 6015: 
 6016: @c -------------------------------------------------------------
 6017: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
 6018: @section Defining Words
 6019: @cindex defining words
 6020: 
 6021: Defining words are used to extend Forth by creating new entries in the dictionary.
 6022: 
 6023: @menu
 6024: * CREATE::                      
 6025: * Variables::                   Variables and user variables
 6026: * Constants::                   
 6027: * Values::                      Initialised variables
 6028: * Colon Definitions::           
 6029: * Anonymous Definitions::       Definitions without names
 6030: * Quotations::                  
 6031: * Supplying names::             Passing definition names as strings
 6032: * User-defined Defining Words::  
 6033: * Deferred Words::              Allow forward references
 6034: * Aliases::                     
 6035: @end menu
 6036: 
 6037: @node CREATE, Variables, Defining Words, Defining Words
 6038: @subsection @code{CREATE}
 6039: @cindex simple defining words
 6040: @cindex defining words, simple
 6041: 
 6042: Defining words are used to create new entries in the dictionary. The
 6043: simplest defining word is @code{CREATE}. @code{CREATE} is used like
 6044: this:
 6045: 
 6046: @example
 6047: CREATE new-word1
 6048: @end example
 6049: 
 6050: @code{CREATE} is a parsing word, i.e., it takes an argument from the
 6051: input stream (@code{new-word1} in our example).  It generates a
 6052: dictionary entry for @code{new-word1}. When @code{new-word1} is
 6053: executed, all that it does is leave an address on the stack. The address
 6054: represents the value of the data space pointer (@code{HERE}) at the time
 6055: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
 6056: associating a name with the address of a region of memory.
 6057: 
 6058: doc-create
 6059: 
 6060: Note that in ANS Forth guarantees only for @code{create} that its body
 6061: is in dictionary data space (i.e., where @code{here}, @code{allot}
 6062: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
 6063: @code{create}d words can be modified with @code{does>}
 6064: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
 6065: can only be applied to @code{create}d words.
 6066: 
 6067: By extending this example to reserve some memory in data space, we end
 6068: up with something like a @i{variable}. Here are two different ways to do
 6069: it:
 6070: 
 6071: @example
 6072: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
 6073: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
 6074: @end example
 6075: 
 6076: The variable can be examined and modified using @code{@@} (``fetch'') and
 6077: @code{!} (``store'') like this:
 6078: 
 6079: @example
 6080: new-word2 @@ .      \ get address, fetch from it and display
 6081: 1234 new-word2 !   \ new value, get address, store to it
 6082: @end example
 6083: 
 6084: @cindex arrays
 6085: A similar mechanism can be used to create arrays. For example, an
 6086: 80-character text input buffer:
 6087: 
 6088: @example
 6089: CREATE text-buf 80 chars allot
 6090: 
 6091: text-buf 0 chars + c@@ \ the 1st character (offset 0)
 6092: text-buf 3 chars + c@@ \ the 4th character (offset 3)
 6093: @end example
 6094: 
 6095: You can build arbitrarily complex data structures by allocating
 6096: appropriate areas of memory. For further discussions of this, and to
 6097: learn about some Gforth tools that make it easier,
 6098: @xref{Structures}.
 6099: 
 6100: 
 6101: @node Variables, Constants, CREATE, Defining Words
 6102: @subsection Variables
 6103: @cindex variables
 6104: 
 6105: The previous section showed how a sequence of commands could be used to
 6106: generate a variable.  As a final refinement, the whole code sequence can
 6107: be wrapped up in a defining word (pre-empting the subject of the next
 6108: section), making it easier to create new variables:
 6109: 
 6110: @example
 6111: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
 6112: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
 6113: 
 6114: myvariableX foo \ variable foo starts off with an unknown value
 6115: myvariable0 joe \ whilst joe is initialised to 0
 6116: 
 6117: 45 3 * foo !   \ set foo to 135
 6118: 1234 joe !     \ set joe to 1234
 6119: 3 joe +!       \ increment joe by 3.. to 1237
 6120: @end example
 6121: 
 6122: Not surprisingly, there is no need to define @code{myvariable}, since
 6123: Forth already has a definition @code{Variable}. ANS Forth does not
 6124: guarantee that a @code{Variable} is initialised when it is created
 6125: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
 6126: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
 6127: like @code{myvariable0}). Forth also provides @code{2Variable} and
 6128: @code{fvariable} for double and floating-point variables, respectively
 6129: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
 6130: store a boolean, you can use @code{on} and @code{off} to toggle its
 6131: state.
 6132: 
 6133: doc-variable
 6134: doc-2variable
 6135: doc-fvariable
 6136: 
 6137: @cindex user variables
 6138: @cindex user space
 6139: The defining word @code{User} behaves in the same way as @code{Variable}.
 6140: The difference is that it reserves space in @i{user (data) space} rather
 6141: than normal data space. In a Forth system that has a multi-tasker, each
 6142: task has its own set of user variables.
 6143: 
 6144: doc-user
 6145: @c doc-udp
 6146: @c doc-uallot
 6147: 
 6148: @comment TODO is that stuff about user variables strictly correct? Is it
 6149: @comment just terminal tasks that have user variables?
 6150: @comment should document tasker.fs (with some examples) elsewhere
 6151: @comment in this manual, then expand on user space and user variables.
 6152: 
 6153: @node Constants, Values, Variables, Defining Words
 6154: @subsection Constants
 6155: @cindex constants
 6156: 
 6157: @code{Constant} allows you to declare a fixed value and refer to it by
 6158: name. For example:
 6159: 
 6160: @example
 6161: 12 Constant INCHES-PER-FOOT
 6162: 3E+08 fconstant SPEED-O-LIGHT
 6163: @end example
 6164: 
 6165: A @code{Variable} can be both read and written, so its run-time
 6166: behaviour is to supply an address through which its current value can be
 6167: manipulated. In contrast, the value of a @code{Constant} cannot be
 6168: changed once it has been declared@footnote{Well, often it can be -- but
 6169: not in a Standard, portable way. It's safer to use a @code{Value} (read
 6170: on).} so it's not necessary to supply the address -- it is more
 6171: efficient to return the value of the constant directly. That's exactly
 6172: what happens; the run-time effect of a constant is to put its value on
 6173: the top of the stack (You can find one
 6174: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
 6175: 
 6176: Forth also provides @code{2Constant} and @code{fconstant} for defining
 6177: double and floating-point constants, respectively.
 6178: 
 6179: doc-constant
 6180: doc-2constant
 6181: doc-fconstant
 6182: 
 6183: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
 6184: @c nac-> How could that not be true in an ANS Forth? You can't define a
 6185: @c constant, use it and then delete the definition of the constant..
 6186: 
 6187: @c anton->An ANS Forth system can compile a constant to a literal; On
 6188: @c decompilation you would see only the number, just as if it had been used
 6189: @c in the first place.  The word will stay, of course, but it will only be
 6190: @c used by the text interpreter (no run-time duties, except when it is 
 6191: @c POSTPONEd or somesuch).
 6192: 
 6193: @c nac:
 6194: @c I agree that it's rather deep, but IMO it is an important difference
 6195: @c relative to other programming languages.. often it's annoying: it
 6196: @c certainly changes my programming style relative to C.
 6197: 
 6198: @c anton: In what way?
 6199: 
 6200: Constants in Forth behave differently from their equivalents in other
 6201: programming languages. In other languages, a constant (such as an EQU in
 6202: assembler or a #define in C) only exists at compile-time; in the
 6203: executable program the constant has been translated into an absolute
 6204: number and, unless you are using a symbolic debugger, it's impossible to
 6205: know what abstract thing that number represents. In Forth a constant has
 6206: an entry in the header space and remains there after the code that uses
 6207: it has been defined. In fact, it must remain in the dictionary since it
 6208: has run-time duties to perform. For example:
 6209: 
 6210: @example
 6211: 12 Constant INCHES-PER-FOOT
 6212: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
 6213: @end example
 6214: 
 6215: @cindex in-lining of constants
 6216: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
 6217: associated with the constant @code{INCHES-PER-FOOT}. If you use
 6218: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
 6219: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
 6220: attempt to optimise constants by in-lining them where they are used. You
 6221: can force Gforth to in-line a constant like this:
 6222: 
 6223: @example
 6224: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
 6225: @end example
 6226: 
 6227: If you use @code{see} to decompile @i{this} version of
 6228: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
 6229: longer present. To understand how this works, read
 6230: @ref{Interpret/Compile states}, and @ref{Literals}.
 6231: 
 6232: In-lining constants in this way might improve execution time
 6233: fractionally, and can ensure that a constant is now only referenced at
 6234: compile-time. However, the definition of the constant still remains in
 6235: the dictionary. Some Forth compilers provide a mechanism for controlling
 6236: a second dictionary for holding transient words such that this second
 6237: dictionary can be deleted later in order to recover memory
 6238: space. However, there is no standard way of doing this.
 6239: 
 6240: 
 6241: @node Values, Colon Definitions, Constants, Defining Words
 6242: @subsection Values
 6243: @cindex values
 6244: 
 6245: A @code{Value} behaves like a @code{Constant}, but it can be changed.
 6246: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
 6247: (not in ANS Forth) you can access (and change) a @code{value} also with
 6248: @code{>body}.
 6249: 
 6250: Here are some
 6251: examples:
 6252: 
 6253: @example
 6254: 12 Value APPLES     \ Define APPLES with an initial value of 12
 6255: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
 6256: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
 6257: APPLES              \ puts 35 on the top of the stack.
 6258: @end example
 6259: 
 6260: doc-value
 6261: doc-to
 6262: 
 6263: 
 6264: 
 6265: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
 6266: @subsection Colon Definitions
 6267: @cindex colon definitions
 6268: 
 6269: @example
 6270: : name ( ... -- ... )
 6271:     word1 word2 word3 ;
 6272: @end example
 6273: 
 6274: @noindent
 6275: Creates a word called @code{name} that, upon execution, executes
 6276: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
 6277: 
 6278: The explanation above is somewhat superficial. For simple examples of
 6279: colon definitions see @ref{Your first definition}.  For an in-depth
 6280: discussion of some of the issues involved, @xref{Interpretation and
 6281: Compilation Semantics}.
 6282: 
 6283: doc-:
 6284: doc-;
 6285: 
 6286: 
 6287: @node Anonymous Definitions, Quotations, Colon Definitions, Defining Words
 6288: @subsection Anonymous Definitions
 6289: @cindex colon definitions
 6290: @cindex defining words without name
 6291: 
 6292: Sometimes you want to define an @dfn{anonymous word}; a word without a
 6293: name. You can do this with:
 6294: 
 6295: doc-:noname
 6296: 
 6297: This leaves the execution token for the word on the stack after the
 6298: closing @code{;}. Here's an example in which a deferred word is
 6299: initialised with an @code{xt} from an anonymous colon definition:
 6300: 
 6301: @example
 6302: Defer deferred
 6303: :noname ( ... -- ... )
 6304:   ... ;
 6305: IS deferred
 6306: @end example
 6307: 
 6308: @noindent
 6309: Gforth provides an alternative way of doing this, using two separate
 6310: words:
 6311: 
 6312: doc-noname
 6313: @cindex execution token of last defined word
 6314: doc-latestxt
 6315: 
 6316: @noindent
 6317: The previous example can be rewritten using @code{noname} and
 6318: @code{latestxt}:
 6319: 
 6320: @example
 6321: Defer deferred
 6322: noname : ( ... -- ... )
 6323:   ... ;
 6324: latestxt IS deferred
 6325: @end example
 6326: 
 6327: @noindent
 6328: @code{noname} works with any defining word, not just @code{:}.
 6329: 
 6330: @code{latestxt} also works when the last word was not defined as
 6331: @code{noname}.  It does not work for combined words, though.  It also has
 6332: the useful property that is is valid as soon as the header for a
 6333: definition has been built. Thus:
 6334: 
 6335: @example
 6336: latestxt . : foo [ latestxt . ] ; ' foo .
 6337: @end example
 6338: 
 6339: @noindent
 6340: prints 3 numbers; the last two are the same.
 6341: 
 6342: 
 6343: @node Quotations, Supplying names, Anonymous Definitions, Defining Words
 6344: @subsection Quotations
 6345: @cindex quotations
 6346: @cindex nested colon definitions
 6347: @cindex colon definitions, nesting
 6348: 
 6349: A quotation is an anonymous colon definition inside another colon
 6350: definition.  Quotations are useful when dealing with words that
 6351: consume an execution token, like @code{catch} or
 6352: @code{outfile-execute}.  E.g. consider the following example of using
 6353: @code{outfile-execute} (@pxref{Redirection}):
 6354: 
 6355: @example
 6356: : some-warning ( n -- )
 6357:     cr ." warning# " . ;
 6358: 
 6359: : print-some-warning ( n -- )
 6360:     ['] some-warning stderr outfile-execute ;
 6361: @end example
 6362: 
 6363: Here we defined @code{some-warning} as a helper word whose xt we could
 6364: pass to outfile-execute.  Instead, we can use a quotation to define
 6365: such a word anonymously inside @code{print-some-warning}:
 6366: 
 6367: @example
 6368: : print-some-warning ( n -- )
 6369:   [: cr ." warning# " . ;] stderr outfile-execute ;
 6370: @end example
 6371: 
 6372: The quotation is bouded by @code{[:} and @code{;]}.  It produces an
 6373: execution token at run-time.
 6374: 
 6375: doc-[:
 6376: doc-;]
 6377: 
 6378: 
 6379: @node Supplying names, User-defined Defining Words, Quotations, Defining Words
 6380: @subsection Supplying the name of a defined word
 6381: @cindex names for defined words
 6382: @cindex defining words, name given in a string
 6383: 
 6384: By default, a defining word takes the name for the defined word from the
 6385: input stream. Sometimes you want to supply the name from a string. You
 6386: can do this with:
 6387: 
 6388: doc-nextname
 6389: 
 6390: For example:
 6391: 
 6392: @example
 6393: s" foo" nextname create
 6394: @end example
 6395: 
 6396: @noindent
 6397: is equivalent to:
 6398: 
 6399: @example
 6400: create foo
 6401: @end example
 6402: 
 6403: @noindent
 6404: @code{nextname} works with any defining word.
 6405: 
 6406: 
 6407: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
 6408: @subsection User-defined Defining Words
 6409: @cindex user-defined defining words
 6410: @cindex defining words, user-defined
 6411: 
 6412: You can create a new defining word by wrapping defining-time code around
 6413: an existing defining word and putting the sequence in a colon
 6414: definition. 
 6415: 
 6416: @c anton: This example is very complex and leads in a quite different
 6417: @c direction from the CREATE-DOES> stuff that follows.  It should probably
 6418: @c be done elsewhere, or as a subsubsection of this subsection (or as a
 6419: @c subsection of Defining Words)
 6420: 
 6421: For example, suppose that you have a word @code{stats} that
 6422: gathers statistics about colon definitions given the @i{xt} of the
 6423: definition, and you want every colon definition in your application to
 6424: make a call to @code{stats}. You can define and use a new version of
 6425: @code{:} like this:
 6426: 
 6427: @example
 6428: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
 6429:   ... ;  \ other code
 6430: 
 6431: : my: : latestxt postpone literal ['] stats compile, ;
 6432: 
 6433: my: foo + - ;
 6434: @end example
 6435: 
 6436: When @code{foo} is defined using @code{my:} these steps occur:
 6437: 
 6438: @itemize @bullet
 6439: @item
 6440: @code{my:} is executed.
 6441: @item
 6442: The @code{:} within the definition (the one between @code{my:} and
 6443: @code{latestxt}) is executed, and does just what it always does; it parses
 6444: the input stream for a name, builds a dictionary header for the name
 6445: @code{foo} and switches @code{state} from interpret to compile.
 6446: @item
 6447: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
 6448: being defined -- @code{foo} -- onto the stack.
 6449: @item
 6450: The code that was produced by @code{postpone literal} is executed; this
 6451: causes the value on the stack to be compiled as a literal in the code
 6452: area of @code{foo}.
 6453: @item
 6454: The code @code{['] stats} compiles a literal into the definition of
 6455: @code{my:}. When @code{compile,} is executed, that literal -- the
 6456: execution token for @code{stats} -- is layed down in the code area of
 6457: @code{foo} , following the literal@footnote{Strictly speaking, the
 6458: mechanism that @code{compile,} uses to convert an @i{xt} into something
 6459: in the code area is implementation-dependent. A threaded implementation
 6460: might spit out the execution token directly whilst another
 6461: implementation might spit out a native code sequence.}.
 6462: @item
 6463: At this point, the execution of @code{my:} is complete, and control
 6464: returns to the text interpreter. The text interpreter is in compile
 6465: state, so subsequent text @code{+ -} is compiled into the definition of
 6466: @code{foo} and the @code{;} terminates the definition as always.
 6467: @end itemize
 6468: 
 6469: You can use @code{see} to decompile a word that was defined using
 6470: @code{my:} and see how it is different from a normal @code{:}
 6471: definition. For example:
 6472: 
 6473: @example
 6474: : bar + - ;  \ like foo but using : rather than my:
 6475: see bar
 6476: : bar
 6477:   + - ;
 6478: see foo
 6479: : foo
 6480:   107645672 stats + - ;
 6481: 
 6482: \ use ' foo . to show that 107645672 is the xt for foo
 6483: @end example
 6484: 
 6485: You can use techniques like this to make new defining words in terms of
 6486: @i{any} existing defining word.
 6487: 
 6488: 
 6489: @cindex defining defining words
 6490: @cindex @code{CREATE} ... @code{DOES>}
 6491: If you want the words defined with your defining words to behave
 6492: differently from words defined with standard defining words, you can
 6493: write your defining word like this:
 6494: 
 6495: @example
 6496: : def-word ( "name" -- )
 6497:     CREATE @i{code1}
 6498: DOES> ( ... -- ... )
 6499:     @i{code2} ;
 6500: 
 6501: def-word name
 6502: @end example
 6503: 
 6504: @cindex child words
 6505: This fragment defines a @dfn{defining word} @code{def-word} and then
 6506: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
 6507: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
 6508: is not executed at this time. The word @code{name} is sometimes called a
 6509: @dfn{child} of @code{def-word}.
 6510: 
 6511: When you execute @code{name}, the address of the body of @code{name} is
 6512: put on the data stack and @i{code2} is executed (the address of the body
 6513: of @code{name} is the address @code{HERE} returns immediately after the
 6514: @code{CREATE}, i.e., the address a @code{create}d word returns by
 6515: default).
 6516: 
 6517: @c anton:
 6518: @c www.dictionary.com says:
 6519: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
 6520: @c several generations of absence, usually caused by the chance
 6521: @c recombination of genes.  2.An individual or a part that exhibits
 6522: @c atavism. Also called throwback.  3.The return of a trait or recurrence
 6523: @c of previous behavior after a period of absence.
 6524: @c
 6525: @c Doesn't seem to fit.
 6526: 
 6527: @c @cindex atavism in child words
 6528: You can use @code{def-word} to define a set of child words that behave
 6529: similarly; they all have a common run-time behaviour determined by
 6530: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
 6531: body of the child word. The structure of the data is common to all
 6532: children of @code{def-word}, but the data values are specific -- and
 6533: private -- to each child word. When a child word is executed, the
 6534: address of its private data area is passed as a parameter on TOS to be
 6535: used and manipulated@footnote{It is legitimate both to read and write to
 6536: this data area.} by @i{code2}.
 6537: 
 6538: The two fragments of code that make up the defining words act (are
 6539: executed) at two completely separate times:
 6540: 
 6541: @itemize @bullet
 6542: @item
 6543: At @i{define time}, the defining word executes @i{code1} to generate a
 6544: child word
 6545: @item
 6546: At @i{child execution time}, when a child word is invoked, @i{code2}
 6547: is executed, using parameters (data) that are private and specific to
 6548: the child word.
 6549: @end itemize
 6550: 
 6551: Another way of understanding the behaviour of @code{def-word} and
 6552: @code{name} is to say that, if you make the following definitions:
 6553: @example
 6554: : def-word1 ( "name" -- )
 6555:     CREATE @i{code1} ;
 6556: 
 6557: : action1 ( ... -- ... )
 6558:     @i{code2} ;
 6559: 
 6560: def-word1 name1
 6561: @end example
 6562: 
 6563: @noindent
 6564: Then using @code{name1 action1} is equivalent to using @code{name}.
 6565: 
 6566: The classic example is that you can define @code{CONSTANT} in this way:
 6567: 
 6568: @example
 6569: : CONSTANT ( w "name" -- )
 6570:     CREATE ,
 6571: DOES> ( -- w )
 6572:     @@ ;
 6573: @end example
 6574: 
 6575: @comment There is a beautiful description of how this works and what
 6576: @comment it does in the Forthwrite 100th edition.. as well as an elegant
 6577: @comment commentary on the Counting Fruits problem.
 6578: 
 6579: When you create a constant with @code{5 CONSTANT five}, a set of
 6580: define-time actions take place; first a new word @code{five} is created,
 6581: then the value 5 is laid down in the body of @code{five} with
 6582: @code{,}. When @code{five} is executed, the address of the body is put on
 6583: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
 6584: no code of its own; it simply contains a data field and a pointer to the
 6585: code that follows @code{DOES>} in its defining word. That makes words
 6586: created in this way very compact.
 6587: 
 6588: The final example in this section is intended to remind you that space
 6589: reserved in @code{CREATE}d words is @i{data} space and therefore can be
 6590: both read and written by a Standard program@footnote{Exercise: use this
 6591: example as a starting point for your own implementation of @code{Value}
 6592: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
 6593: @code{[']}.}:
 6594: 
 6595: @example
 6596: : foo ( "name" -- )
 6597:     CREATE -1 ,
 6598: DOES> ( -- )
 6599:     @@ . ;
 6600: 
 6601: foo first-word
 6602: foo second-word
 6603: 
 6604: 123 ' first-word >BODY !
 6605: @end example
 6606: 
 6607: If @code{first-word} had been a @code{CREATE}d word, we could simply
 6608: have executed it to get the address of its data field. However, since it
 6609: was defined to have @code{DOES>} actions, its execution semantics are to
 6610: perform those @code{DOES>} actions. To get the address of its data field
 6611: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
 6612: translate the xt into the address of the data field.  When you execute
 6613: @code{first-word}, it will display @code{123}. When you execute
 6614: @code{second-word} it will display @code{-1}.
 6615: 
 6616: @cindex stack effect of @code{DOES>}-parts
 6617: @cindex @code{DOES>}-parts, stack effect
 6618: In the examples above the stack comment after the @code{DOES>} specifies
 6619: the stack effect of the defined words, not the stack effect of the
 6620: following code (the following code expects the address of the body on
 6621: the top of stack, which is not reflected in the stack comment). This is
 6622: the convention that I use and recommend (it clashes a bit with using
 6623: locals declarations for stack effect specification, though).
 6624: 
 6625: @menu
 6626: * CREATE..DOES> applications::  
 6627: * CREATE..DOES> details::       
 6628: * Advanced does> usage example::  
 6629: * Const-does>::                 
 6630: @end menu
 6631: 
 6632: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
 6633: @subsubsection Applications of @code{CREATE..DOES>}
 6634: @cindex @code{CREATE} ... @code{DOES>}, applications
 6635: 
 6636: You may wonder how to use this feature. Here are some usage patterns:
 6637: 
 6638: @cindex factoring similar colon definitions
 6639: When you see a sequence of code occurring several times, and you can
 6640: identify a meaning, you will factor it out as a colon definition. When
 6641: you see similar colon definitions, you can factor them using
 6642: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
 6643: that look very similar:
 6644: @example
 6645: : ori, ( reg-target reg-source n -- )
 6646:     0 asm-reg-reg-imm ;
 6647: : andi, ( reg-target reg-source n -- )
 6648:     1 asm-reg-reg-imm ;
 6649: @end example
 6650: 
 6651: @noindent
 6652: This could be factored with:
 6653: @example
 6654: : reg-reg-imm ( op-code -- )
 6655:     CREATE ,
 6656: DOES> ( reg-target reg-source n -- )
 6657:     @@ asm-reg-reg-imm ;
 6658: 
 6659: 0 reg-reg-imm ori,
 6660: 1 reg-reg-imm andi,
 6661: @end example
 6662: 
 6663: @cindex currying
 6664: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
 6665: supply a part of the parameters for a word (known as @dfn{currying} in
 6666: the functional language community). E.g., @code{+} needs two
 6667: parameters. Creating versions of @code{+} with one parameter fixed can
 6668: be done like this:
 6669: 
 6670: @example
 6671: : curry+ ( n1 "name" -- )
 6672:     CREATE ,
 6673: DOES> ( n2 -- n1+n2 )
 6674:     @@ + ;
 6675: 
 6676:  3 curry+ 3+
 6677: -2 curry+ 2-
 6678: @end example
 6679: 
 6680: 
 6681: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
 6682: @subsubsection The gory details of @code{CREATE..DOES>}
 6683: @cindex @code{CREATE} ... @code{DOES>}, details
 6684: 
 6685: doc-does>
 6686: 
 6687: @cindex @code{DOES>} in a separate definition
 6688: This means that you need not use @code{CREATE} and @code{DOES>} in the
 6689: same definition; you can put the @code{DOES>}-part in a separate
 6690: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
 6691: @example
 6692: : does1 
 6693: DOES> ( ... -- ... )
 6694:     ... ;
 6695: 
 6696: : does2
 6697: DOES> ( ... -- ... )
 6698:     ... ;
 6699: 
 6700: : def-word ( ... -- ... )
 6701:     create ...
 6702:     IF
 6703:        does1
 6704:     ELSE
 6705:        does2
 6706:     ENDIF ;
 6707: @end example
 6708: 
 6709: In this example, the selection of whether to use @code{does1} or
 6710: @code{does2} is made at definition-time; at the time that the child word is
 6711: @code{CREATE}d.
 6712: 
 6713: @cindex @code{DOES>} in interpretation state
 6714: In a standard program you can apply a @code{DOES>}-part only if the last
 6715: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
 6716: will override the behaviour of the last word defined in any case. In a
 6717: standard program, you can use @code{DOES>} only in a colon
 6718: definition. In Gforth, you can also use it in interpretation state, in a
 6719: kind of one-shot mode; for example:
 6720: @example
 6721: CREATE name ( ... -- ... )
 6722:   @i{initialization}
 6723: DOES>
 6724:   @i{code} ;
 6725: @end example
 6726: 
 6727: @noindent
 6728: is equivalent to the standard:
 6729: @example
 6730: :noname
 6731: DOES>
 6732:     @i{code} ;
 6733: CREATE name EXECUTE ( ... -- ... )
 6734:     @i{initialization}
 6735: @end example
 6736: 
 6737: doc->body
 6738: 
 6739: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
 6740: @subsubsection Advanced does> usage example
 6741: 
 6742: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
 6743: for disassembling instructions, that follow a very repetetive scheme:
 6744: 
 6745: @example
 6746: :noname @var{disasm-operands} s" @var{inst-name}" type ;
 6747: @var{entry-num} cells @var{table} + !
 6748: @end example
 6749: 
 6750: Of course, this inspires the idea to factor out the commonalities to
 6751: allow a definition like
 6752: 
 6753: @example
 6754: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
 6755: @end example
 6756: 
 6757: The parameters @var{disasm-operands} and @var{table} are usually
 6758: correlated.  Moreover, before I wrote the disassembler, there already
 6759: existed code that defines instructions like this:
 6760: 
 6761: @example
 6762: @var{entry-num} @var{inst-format} @var{inst-name}
 6763: @end example
 6764: 
 6765: This code comes from the assembler and resides in
 6766: @file{arch/mips/insts.fs}.
 6767: 
 6768: So I had to define the @var{inst-format} words that performed the scheme
 6769: above when executed.  At first I chose to use run-time code-generation:
 6770: 
 6771: @example
 6772: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
 6773:   :noname Postpone @var{disasm-operands}
 6774:   name Postpone sliteral Postpone type Postpone ;
 6775:   swap cells @var{table} + ! ;
 6776: @end example
 6777: 
 6778: Note that this supplies the other two parameters of the scheme above.
 6779: 
 6780: An alternative would have been to write this using
 6781: @code{create}/@code{does>}:
 6782: 
 6783: @example
 6784: : @var{inst-format} ( entry-num "name" -- )
 6785:   here name string, ( entry-num c-addr ) \ parse and save "name"
 6786:   noname create , ( entry-num )
 6787:   latestxt swap cells @var{table} + !
 6788: does> ( addr w -- )
 6789:   \ disassemble instruction w at addr
 6790:   @@ >r 
 6791:   @var{disasm-operands}
 6792:   r> count type ;
 6793: @end example
 6794: 
 6795: Somehow the first solution is simpler, mainly because it's simpler to
 6796: shift a string from definition-time to use-time with @code{sliteral}
 6797: than with @code{string,} and friends.
 6798: 
 6799: I wrote a lot of words following this scheme and soon thought about
 6800: factoring out the commonalities among them.  Note that this uses a
 6801: two-level defining word, i.e., a word that defines ordinary defining
 6802: words.
 6803: 
 6804: This time a solution involving @code{postpone} and friends seemed more
 6805: difficult (try it as an exercise), so I decided to use a
 6806: @code{create}/@code{does>} word; since I was already at it, I also used
 6807: @code{create}/@code{does>} for the lower level (try using
 6808: @code{postpone} etc. as an exercise), resulting in the following
 6809: definition:
 6810: 
 6811: @example
 6812: : define-format ( disasm-xt table-xt -- )
 6813:     \ define an instruction format that uses disasm-xt for
 6814:     \ disassembling and enters the defined instructions into table
 6815:     \ table-xt
 6816:     create 2,
 6817: does> ( u "inst" -- )
 6818:     \ defines an anonymous word for disassembling instruction inst,
 6819:     \ and enters it as u-th entry into table-xt
 6820:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
 6821:     noname create 2,      \ define anonymous word
 6822:     execute latestxt swap ! \ enter xt of defined word into table-xt
 6823: does> ( addr w -- )
 6824:     \ disassemble instruction w at addr
 6825:     2@@ >r ( addr w disasm-xt R: c-addr )
 6826:     execute ( R: c-addr ) \ disassemble operands
 6827:     r> count type ; \ print name 
 6828: @end example
 6829: 
 6830: Note that the tables here (in contrast to above) do the @code{cells +}
 6831: by themselves (that's why you have to pass an xt).  This word is used in
 6832: the following way:
 6833: 
 6834: @example
 6835: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
 6836: @end example
 6837: 
 6838: As shown above, the defined instruction format is then used like this:
 6839: 
 6840: @example
 6841: @var{entry-num} @var{inst-format} @var{inst-name}
 6842: @end example
 6843: 
 6844: In terms of currying, this kind of two-level defining word provides the
 6845: parameters in three stages: first @var{disasm-operands} and @var{table},
 6846: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
 6847: the instruction to be disassembled.  
 6848: 
 6849: Of course this did not quite fit all the instruction format names used
 6850: in @file{insts.fs}, so I had to define a few wrappers that conditioned
 6851: the parameters into the right form.
 6852: 
 6853: If you have trouble following this section, don't worry.  First, this is
 6854: involved and takes time (and probably some playing around) to
 6855: understand; second, this is the first two-level
 6856: @code{create}/@code{does>} word I have written in seventeen years of
 6857: Forth; and if I did not have @file{insts.fs} to start with, I may well
 6858: have elected to use just a one-level defining word (with some repeating
 6859: of parameters when using the defining word). So it is not necessary to
 6860: understand this, but it may improve your understanding of Forth.
 6861: 
 6862: 
 6863: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
 6864: @subsubsection @code{Const-does>}
 6865: 
 6866: A frequent use of @code{create}...@code{does>} is for transferring some
 6867: values from definition-time to run-time.  Gforth supports this use with
 6868: 
 6869: doc-const-does>
 6870: 
 6871: A typical use of this word is:
 6872: 
 6873: @example
 6874: : curry+ ( n1 "name" -- )
 6875: 1 0 CONST-DOES> ( n2 -- n1+n2 )
 6876:     + ;
 6877: 
 6878: 3 curry+ 3+
 6879: @end example
 6880: 
 6881: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
 6882: definition to run-time.
 6883: 
 6884: The advantages of using @code{const-does>} are:
 6885: 
 6886: @itemize
 6887: 
 6888: @item
 6889: You don't have to deal with storing and retrieving the values, i.e.,
 6890: your program becomes more writable and readable.
 6891: 
 6892: @item
 6893: When using @code{does>}, you have to introduce a @code{@@} that cannot
 6894: be optimized away (because you could change the data using
 6895: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
 6896: 
 6897: @end itemize
 6898: 
 6899: An ANS Forth implementation of @code{const-does>} is available in
 6900: @file{compat/const-does.fs}.
 6901: 
 6902: 
 6903: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
 6904: @subsection Deferred Words
 6905: @cindex deferred words
 6906: 
 6907: The defining word @code{Defer} allows you to define a word by name
 6908: without defining its behaviour; the definition of its behaviour is
 6909: deferred. Here are two situation where this can be useful:
 6910: 
 6911: @itemize @bullet
 6912: @item
 6913: Where you want to allow the behaviour of a word to be altered later, and
 6914: for all precompiled references to the word to change when its behaviour
 6915: is changed.
 6916: @item
 6917: For mutual recursion; @xref{Calls and returns}.
 6918: @end itemize
 6919: 
 6920: In the following example, @code{foo} always invokes the version of
 6921: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
 6922: always invokes the version that prints ``@code{Hello}''. There is no way
 6923: of getting @code{foo} to use the later version without re-ordering the
 6924: source code and recompiling it.
 6925: 
 6926: @example
 6927: : greet ." Good morning" ;
 6928: : foo ... greet ... ;
 6929: : greet ." Hello" ;
 6930: : bar ... greet ... ;
 6931: @end example
 6932: 
 6933: This problem can be solved by defining @code{greet} as a @code{Defer}red
 6934: word. The behaviour of a @code{Defer}red word can be defined and
 6935: redefined at any time by using @code{IS} to associate the xt of a
 6936: previously-defined word with it. The previous example becomes:
 6937: 
 6938: @example
 6939: Defer greet ( -- )
 6940: : foo ... greet ... ;
 6941: : bar ... greet ... ;
 6942: : greet1 ( -- ) ." Good morning" ;
 6943: : greet2 ( -- ) ." Hello" ;
 6944: ' greet2 IS greet  \ make greet behave like greet2
 6945: @end example
 6946: 
 6947: @progstyle
 6948: You should write a stack comment for every deferred word, and put only
 6949: XTs into deferred words that conform to this stack effect.  Otherwise
 6950: it's too difficult to use the deferred word.
 6951: 
 6952: A deferred word can be used to improve the statistics-gathering example
 6953: from @ref{User-defined Defining Words}; rather than edit the
 6954: application's source code to change every @code{:} to a @code{my:}, do
 6955: this:
 6956: 
 6957: @example
 6958: : real: : ;     \ retain access to the original
 6959: defer :         \ redefine as a deferred word
 6960: ' my: IS :      \ use special version of :
 6961: \
 6962: \ load application here
 6963: \
 6964: ' real: IS :    \ go back to the original
 6965: @end example
 6966: 
 6967: 
 6968: One thing to note is that @code{IS} has special compilation semantics,
 6969: such that it parses the name at compile time (like @code{TO}):
 6970: 
 6971: @example
 6972: : set-greet ( xt -- )
 6973:   IS greet ;
 6974: 
 6975: ' greet1 set-greet
 6976: @end example
 6977: 
 6978: In situations where @code{IS} does not fit, use @code{defer!} instead.
 6979: 
 6980: A deferred word can only inherit execution semantics from the xt
 6981: (because that is all that an xt can represent -- for more discussion of
 6982: this @pxref{Tokens for Words}); by default it will have default
 6983: interpretation and compilation semantics deriving from this execution
 6984: semantics.  However, you can change the interpretation and compilation
 6985: semantics of the deferred word in the usual ways:
 6986: 
 6987: @example
 6988: : bar .... ; immediate
 6989: Defer fred immediate
 6990: Defer jim
 6991: 
 6992: ' bar IS jim  \ jim has default semantics
 6993: ' bar IS fred \ fred is immediate
 6994: @end example
 6995: 
 6996: doc-defer
 6997: doc-defer!
 6998: doc-is
 6999: doc-defer@
 7000: doc-action-of
 7001: @comment TODO document these: what's defers [is]
 7002: doc-defers
 7003: 
 7004: @c Use @code{words-deferred} to see a list of deferred words.
 7005: 
 7006: Definitions of these words (except @code{defers}) in ANS Forth are
 7007: provided in @file{compat/defer.fs}.
 7008: 
 7009: 
 7010: @node Aliases,  , Deferred Words, Defining Words
 7011: @subsection Aliases
 7012: @cindex aliases
 7013: 
 7014: The defining word @code{Alias} allows you to define a word by name that
 7015: has the same behaviour as some other word. Here are two situation where
 7016: this can be useful:
 7017: 
 7018: @itemize @bullet
 7019: @item
 7020: When you want access to a word's definition from a different word list
 7021: (for an example of this, see the definition of the @code{Root} word list
 7022: in the Gforth source).
 7023: @item
 7024: When you want to create a synonym; a definition that can be known by
 7025: either of two names (for example, @code{THEN} and @code{ENDIF} are
 7026: aliases).
 7027: @end itemize
 7028: 
 7029: Like deferred words, an alias has default compilation and interpretation
 7030: semantics at the beginning (not the modifications of the other word),
 7031: but you can change them in the usual ways (@code{immediate},
 7032: @code{compile-only}). For example:
 7033: 
 7034: @example
 7035: : foo ... ; immediate
 7036: 
 7037: ' foo Alias bar \ bar is not an immediate word
 7038: ' foo Alias fooby immediate \ fooby is an immediate word
 7039: @end example
 7040: 
 7041: Words that are aliases have the same xt, different headers in the
 7042: dictionary, and consequently different name tokens (@pxref{Tokens for
 7043: Words}) and possibly different immediate flags.  An alias can only have
 7044: default or immediate compilation semantics; you can define aliases for
 7045: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
 7046: 
 7047: doc-alias
 7048: 
 7049: 
 7050: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
 7051: @section Interpretation and Compilation Semantics
 7052: @cindex semantics, interpretation and compilation
 7053: 
 7054: @c !! state and ' are used without explanation
 7055: @c example for immediate/compile-only? or is the tutorial enough
 7056: 
 7057: @cindex interpretation semantics
 7058: The @dfn{interpretation semantics} of a (named) word are what the text
 7059: interpreter does when it encounters the word in interpret state. It also
 7060: appears in some other contexts, e.g., the execution token returned by
 7061: @code{' @i{word}} identifies the interpretation semantics of @i{word}
 7062: (in other words, @code{' @i{word} execute} is equivalent to
 7063: interpret-state text interpretation of @code{@i{word}}).
 7064: 
 7065: @cindex compilation semantics
 7066: The @dfn{compilation semantics} of a (named) word are what the text
 7067: interpreter does when it encounters the word in compile state. It also
 7068: appears in other contexts, e.g, @code{POSTPONE @i{word}}
 7069: compiles@footnote{In standard terminology, ``appends to the current
 7070: definition''.} the compilation semantics of @i{word}.
 7071: 
 7072: @cindex execution semantics
 7073: The standard also talks about @dfn{execution semantics}. They are used
 7074: only for defining the interpretation and compilation semantics of many
 7075: words. By default, the interpretation semantics of a word are to
 7076: @code{execute} its execution semantics, and the compilation semantics of
 7077: a word are to @code{compile,} its execution semantics.@footnote{In
 7078: standard terminology: The default interpretation semantics are its
 7079: execution semantics; the default compilation semantics are to append its
 7080: execution semantics to the execution semantics of the current
 7081: definition.}
 7082: 
 7083: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
 7084: the text interpreter, ticked, or @code{postpone}d, so they have no
 7085: interpretation or compilation semantics.  Their behaviour is represented
 7086: by their XT (@pxref{Tokens for Words}), and we call it execution
 7087: semantics, too.
 7088: 
 7089: @comment TODO expand, make it co-operate with new sections on text interpreter.
 7090: 
 7091: @cindex immediate words
 7092: @cindex compile-only words
 7093: You can change the semantics of the most-recently defined word:
 7094: 
 7095: 
 7096: doc-immediate
 7097: doc-compile-only
 7098: doc-restrict
 7099: 
 7100: By convention, words with non-default compilation semantics (e.g.,
 7101: immediate words) often have names surrounded with brackets (e.g.,
 7102: @code{[']}, @pxref{Execution token}).
 7103: 
 7104: Note that ticking (@code{'}) a compile-only word gives an error
 7105: (``Interpreting a compile-only word'').
 7106: 
 7107: @menu
 7108: * Combined words::              
 7109: @end menu
 7110: 
 7111: 
 7112: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
 7113: @subsection Combined Words
 7114: @cindex combined words
 7115: 
 7116: Gforth allows you to define @dfn{combined words} -- words that have an
 7117: arbitrary combination of interpretation and compilation semantics.
 7118: 
 7119: doc-interpret/compile:
 7120: 
 7121: This feature was introduced for implementing @code{TO} and @code{S"}. I
 7122: recommend that you do not define such words, as cute as they may be:
 7123: they make it hard to get at both parts of the word in some contexts.
 7124: E.g., assume you want to get an execution token for the compilation
 7125: part. Instead, define two words, one that embodies the interpretation
 7126: part, and one that embodies the compilation part.  Once you have done
 7127: that, you can define a combined word with @code{interpret/compile:} for
 7128: the convenience of your users.
 7129: 
 7130: You might try to use this feature to provide an optimizing
 7131: implementation of the default compilation semantics of a word. For
 7132: example, by defining:
 7133: @example
 7134: :noname
 7135:    foo bar ;
 7136: :noname
 7137:    POSTPONE foo POSTPONE bar ;
 7138: interpret/compile: opti-foobar
 7139: @end example
 7140: 
 7141: @noindent
 7142: as an optimizing version of:
 7143: 
 7144: @example
 7145: : foobar
 7146:     foo bar ;
 7147: @end example
 7148: 
 7149: Unfortunately, this does not work correctly with @code{[compile]},
 7150: because @code{[compile]} assumes that the compilation semantics of all
 7151: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
 7152: opti-foobar} would compile compilation semantics, whereas
 7153: @code{[compile] foobar} would compile interpretation semantics.
 7154: 
 7155: @cindex state-smart words (are a bad idea)
 7156: @anchor{state-smartness}
 7157: Some people try to use @dfn{state-smart} words to emulate the feature provided
 7158: by @code{interpret/compile:} (words are state-smart if they check
 7159: @code{STATE} during execution). E.g., they would try to code
 7160: @code{foobar} like this:
 7161: 
 7162: @example
 7163: : foobar
 7164:   STATE @@
 7165:   IF ( compilation state )
 7166:     POSTPONE foo POSTPONE bar
 7167:   ELSE
 7168:     foo bar
 7169:   ENDIF ; immediate
 7170: @end example
 7171: 
 7172: Although this works if @code{foobar} is only processed by the text
 7173: interpreter, it does not work in other contexts (like @code{'} or
 7174: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
 7175: for a state-smart word, not for the interpretation semantics of the
 7176: original @code{foobar}; when you execute this execution token (directly
 7177: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
 7178: state, the result will not be what you expected (i.e., it will not
 7179: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
 7180: write them@footnote{For a more detailed discussion of this topic, see
 7181: M. Anton Ertl,
 7182: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
 7183: it is Evil and How to Exorcise it}}, EuroForth '98.}!
 7184: 
 7185: @cindex defining words with arbitrary semantics combinations
 7186: It is also possible to write defining words that define words with
 7187: arbitrary combinations of interpretation and compilation semantics. In
 7188: general, they look like this:
 7189: 
 7190: @example
 7191: : def-word
 7192:     create-interpret/compile
 7193:     @i{code1}
 7194: interpretation>
 7195:     @i{code2}
 7196: <interpretation
 7197: compilation>
 7198:     @i{code3}
 7199: <compilation ;
 7200: @end example
 7201: 
 7202: For a @i{word} defined with @code{def-word}, the interpretation
 7203: semantics are to push the address of the body of @i{word} and perform
 7204: @i{code2}, and the compilation semantics are to push the address of
 7205: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
 7206: can also be defined like this (except that the defined constants don't
 7207: behave correctly when @code{[compile]}d):
 7208: 
 7209: @example
 7210: : constant ( n "name" -- )
 7211:     create-interpret/compile
 7212:     ,
 7213: interpretation> ( -- n )
 7214:     @@
 7215: <interpretation
 7216: compilation> ( compilation. -- ; run-time. -- n )
 7217:     @@ postpone literal
 7218: <compilation ;
 7219: @end example
 7220: 
 7221: 
 7222: doc-create-interpret/compile
 7223: doc-interpretation>
 7224: doc-<interpretation
 7225: doc-compilation>
 7226: doc-<compilation
 7227: 
 7228: 
 7229: Words defined with @code{interpret/compile:} and
 7230: @code{create-interpret/compile} have an extended header structure that
 7231: differs from other words; however, unless you try to access them with
 7232: plain address arithmetic, you should not notice this. Words for
 7233: accessing the header structure usually know how to deal with this; e.g.,
 7234: @code{'} @i{word} @code{>body} also gives you the body of a word created
 7235: with @code{create-interpret/compile}.
 7236: 
 7237: 
 7238: @c -------------------------------------------------------------
 7239: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
 7240: @section Tokens for Words
 7241: @cindex tokens for words
 7242: 
 7243: This section describes the creation and use of tokens that represent
 7244: words.
 7245: 
 7246: @menu
 7247: * Execution token::             represents execution/interpretation semantics
 7248: * Compilation token::           represents compilation semantics
 7249: * Name token::                  represents named words
 7250: @end menu
 7251: 
 7252: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
 7253: @subsection Execution token
 7254: 
 7255: @cindex xt
 7256: @cindex execution token
 7257: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
 7258: You can use @code{execute} to invoke this behaviour.
 7259: 
 7260: @cindex tick (')
 7261: You can use @code{'} to get an execution token that represents the
 7262: interpretation semantics of a named word:
 7263: 
 7264: @example
 7265: 5 ' .   ( n xt ) 
 7266: execute ( )      \ execute the xt (i.e., ".")
 7267: @end example
 7268: 
 7269: doc-'
 7270: 
 7271: @code{'} parses at run-time; there is also a word @code{[']} that parses
 7272: when it is compiled, and compiles the resulting XT:
 7273: 
 7274: @example
 7275: : foo ['] . execute ;
 7276: 5 foo
 7277: : bar ' execute ; \ by contrast,
 7278: 5 bar .           \ ' parses "." when bar executes
 7279: @end example
 7280: 
 7281: doc-[']
 7282: 
 7283: If you want the execution token of @i{word}, write @code{['] @i{word}}
 7284: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
 7285: @code{'} and @code{[']} behave somewhat unusually by complaining about
 7286: compile-only words (because these words have no interpretation
 7287: semantics).  You might get what you want by using @code{COMP' @i{word}
 7288: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
 7289: token}).
 7290: 
 7291: Another way to get an XT is @code{:noname} or @code{latestxt}
 7292: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
 7293: for the only behaviour the word has (the execution semantics).  For
 7294: named words, @code{latestxt} produces an XT for the same behaviour it
 7295: would produce if the word was defined anonymously.
 7296: 
 7297: @example
 7298: :noname ." hello" ;
 7299: execute
 7300: @end example
 7301: 
 7302: An XT occupies one cell and can be manipulated like any other cell.
 7303: 
 7304: @cindex code field address
 7305: @cindex CFA
 7306: In ANS Forth the XT is just an abstract data type (i.e., defined by the
 7307: operations that produce or consume it).  For old hands: In Gforth, the
 7308: XT is implemented as a code field address (CFA).
 7309: 
 7310: doc-execute
 7311: doc-perform
 7312: 
 7313: @node Compilation token, Name token, Execution token, Tokens for Words
 7314: @subsection Compilation token
 7315: 
 7316: @cindex compilation token
 7317: @cindex CT (compilation token)
 7318: Gforth represents the compilation semantics of a named word by a
 7319: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
 7320: @i{xt} is an execution token. The compilation semantics represented by
 7321: the compilation token can be performed with @code{execute}, which
 7322: consumes the whole compilation token, with an additional stack effect
 7323: determined by the represented compilation semantics.
 7324: 
 7325: At present, the @i{w} part of a compilation token is an execution token,
 7326: and the @i{xt} part represents either @code{execute} or
 7327: @code{compile,}@footnote{Depending upon the compilation semantics of the
 7328: word. If the word has default compilation semantics, the @i{xt} will
 7329: represent @code{compile,}. Otherwise (e.g., for immediate words), the
 7330: @i{xt} will represent @code{execute}.}. However, don't rely on that
 7331: knowledge, unless necessary; future versions of Gforth may introduce
 7332: unusual compilation tokens (e.g., a compilation token that represents
 7333: the compilation semantics of a literal).
 7334: 
 7335: You can perform the compilation semantics represented by the compilation
 7336: token with @code{execute}.  You can compile the compilation semantics
 7337: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
 7338: equivalent to @code{postpone @i{word}}.
 7339: 
 7340: doc-[comp']
 7341: doc-comp'
 7342: doc-postpone,
 7343: 
 7344: @node Name token,  , Compilation token, Tokens for Words
 7345: @subsection Name token
 7346: 
 7347: @cindex name token
 7348: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
 7349: token is an abstract data type that occurs as argument or result of the
 7350: words below.
 7351: 
 7352: @c !! put this elswhere?
 7353: @cindex name field address
 7354: @cindex NFA
 7355: The closest thing to the nt in older Forth systems is the name field
 7356: address (NFA), but there are significant differences: in older Forth
 7357: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
 7358: LFA, NFA, CFA, PFA) and there were words for getting from one to the
 7359: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
 7360: is a link field in the structure identified by the name token, but
 7361: searching usually uses a hash table external to these structures; the
 7362: name in Gforth has a cell-wide count-and-flags field, and the nt is not
 7363: implemented as the address of that count field.
 7364: 
 7365: doc-find-name
 7366: doc-latest
 7367: doc->name
 7368: doc-name>int
 7369: doc-name?int
 7370: doc-name>comp
 7371: doc-name>string
 7372: doc-id.
 7373: doc-.name
 7374: doc-.id
 7375: 
 7376: @c ----------------------------------------------------------
 7377: @node Compiling words, The Text Interpreter, Tokens for Words, Words
 7378: @section Compiling words
 7379: @cindex compiling words
 7380: @cindex macros
 7381: 
 7382: In contrast to most other languages, Forth has no strict boundary
 7383: between compilation and run-time.  E.g., you can run arbitrary code
 7384: between defining words (or for computing data used by defining words
 7385: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
 7386: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
 7387: running arbitrary code while compiling a colon definition (exception:
 7388: you must not allot dictionary space).
 7389: 
 7390: @menu
 7391: * Literals::                    Compiling data values
 7392: * Macros::                      Compiling words
 7393: @end menu
 7394: 
 7395: @node Literals, Macros, Compiling words, Compiling words
 7396: @subsection Literals
 7397: @cindex Literals
 7398: 
 7399: The simplest and most frequent example is to compute a literal during
 7400: compilation.  E.g., the following definition prints an array of strings,
 7401: one string per line:
 7402: 
 7403: @example
 7404: : .strings ( addr u -- ) \ gforth
 7405:     2* cells bounds U+DO
 7406: 	cr i 2@@ type
 7407:     2 cells +LOOP ;  
 7408: @end example
 7409: 
 7410: With a simple-minded compiler like Gforth's, this computes @code{2
 7411: cells} on every loop iteration.  You can compute this value once and for
 7412: all at compile time and compile it into the definition like this:
 7413: 
 7414: @example
 7415: : .strings ( addr u -- ) \ gforth
 7416:     2* cells bounds U+DO
 7417: 	cr i 2@@ type
 7418:     [ 2 cells ] literal +LOOP ;  
 7419: @end example
 7420: 
 7421: @code{[} switches the text interpreter to interpret state (you will get
 7422: an @code{ok} prompt if you type this example interactively and insert a
 7423: newline between @code{[} and @code{]}), so it performs the
 7424: interpretation semantics of @code{2 cells}; this computes a number.
 7425: @code{]} switches the text interpreter back into compile state.  It then
 7426: performs @code{Literal}'s compilation semantics, which are to compile
 7427: this number into the current word.  You can decompile the word with
 7428: @code{see .strings} to see the effect on the compiled code.
 7429: 
 7430: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
 7431: *} in this way.
 7432: 
 7433: doc-[
 7434: doc-]
 7435: doc-literal
 7436: doc-]L
 7437: 
 7438: There are also words for compiling other data types than single cells as
 7439: literals:
 7440: 
 7441: doc-2literal
 7442: doc-fliteral
 7443: doc-sliteral
 7444: 
 7445: @cindex colon-sys, passing data across @code{:}
 7446: @cindex @code{:}, passing data across
 7447: You might be tempted to pass data from outside a colon definition to the
 7448: inside on the data stack.  This does not work, because @code{:} puhes a
 7449: colon-sys, making stuff below unaccessible.  E.g., this does not work:
 7450: 
 7451: @example
 7452: 5 : foo literal ; \ error: "unstructured"
 7453: @end example
 7454: 
 7455: Instead, you have to pass the value in some other way, e.g., through a
 7456: variable:
 7457: 
 7458: @example
 7459: variable temp
 7460: 5 temp !
 7461: : foo [ temp @@ ] literal ;
 7462: @end example
 7463: 
 7464: 
 7465: @node Macros,  , Literals, Compiling words
 7466: @subsection Macros
 7467: @cindex Macros
 7468: @cindex compiling compilation semantics
 7469: 
 7470: @code{Literal} and friends compile data values into the current
 7471: definition.  You can also write words that compile other words into the
 7472: current definition.  E.g.,
 7473: 
 7474: @example
 7475: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
 7476:   POSTPONE + ;
 7477: 
 7478: : foo ( n1 n2 -- n )
 7479:   [ compile-+ ] ;
 7480: 1 2 foo .
 7481: @end example
 7482: 
 7483: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
 7484: What happens in this example?  @code{Postpone} compiles the compilation
 7485: semantics of @code{+} into @code{compile-+}; later the text interpreter
 7486: executes @code{compile-+} and thus the compilation semantics of +, which
 7487: compile (the execution semantics of) @code{+} into
 7488: @code{foo}.@footnote{A recent RFI answer requires that compiling words
 7489: should only be executed in compile state, so this example is not
 7490: guaranteed to work on all standard systems, but on any decent system it
 7491: will work.}
 7492: 
 7493: doc-postpone
 7494: 
 7495: Compiling words like @code{compile-+} are usually immediate (or similar)
 7496: so you do not have to switch to interpret state to execute them;
 7497: modifying the last example accordingly produces:
 7498: 
 7499: @example
 7500: : [compile-+] ( compilation: --; interpretation: -- )
 7501:   \ compiled code: ( n1 n2 -- n )
 7502:   POSTPONE + ; immediate
 7503: 
 7504: : foo ( n1 n2 -- n )
 7505:   [compile-+] ;
 7506: 1 2 foo .
 7507: @end example
 7508: 
 7509: You will occassionally find the need to POSTPONE several words;
 7510: putting POSTPONE before each such word is cumbersome, so Gforth
 7511: provides a more convenient syntax: @code{]] ... [[}.  This
 7512: allows us to write @code{[compile-+]} as:
 7513: 
 7514: @example
 7515: : [compile-+] ( compilation: --; interpretation: -- )
 7516:   ]] + [[ ; immediate
 7517: @end example
 7518: 
 7519: doc-]]
 7520: doc-[[
 7521: 
 7522: The unusual direction of the brackets indicates their function:
 7523: @code{]]} switches from compilation to postponing (i.e., compilation
 7524: of compilation), just like @code{]} switches from immediate execution
 7525: (interpretation) to compilation.  Conversely, @code{[[} switches from
 7526: postponing to compilation, ananlogous to @code{[} which switches from
 7527: compilation to immediate execution.
 7528: 
 7529: The real advantage of @code{]] }...@code{ [[} becomes apparent when
 7530: there are many words to POSTPONE.  E.g., the word
 7531: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
 7532: written much shorter as follows:
 7533: 
 7534: @example
 7535: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
 7536: \ at run-time, execute xt ( ... x -- ... ) for each element of the
 7537: \ array beginning at addr and containing u elements
 7538:   @{ xt @}
 7539:   ]] cells over + swap ?do
 7540:     i @@ [[ xt compile, 
 7541:   1 cells ]]L +loop [[ ;
 7542: @end example
 7543: 
 7544: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
 7545: There are also other shortcuts
 7546: 
 7547: doc-]]L
 7548: doc-]]2L
 7549: doc-]]FL
 7550: doc-]]SL
 7551: 
 7552: Note that parsing words don't parse at postpone time; if you want to
 7553: provide the parsed string right away, you have to switch back to
 7554: compilation:
 7555: 
 7556: @example
 7557: ]] ... [[ s" some string" ]]2L ... [[
 7558: ]] ... [[ ['] + ]]L ... [[
 7559: @end example
 7560: 
 7561: Definitions of @code{]]} and friends in ANS Forth are provided in
 7562: @file{compat/macros.fs}.
 7563: 
 7564: Immediate compiling words are similar to macros in other languages (in
 7565: particular, Lisp).  The important differences to macros in, e.g., C are:
 7566: 
 7567: @itemize @bullet
 7568: 
 7569: @item
 7570: You use the same language for defining and processing macros, not a
 7571: separate preprocessing language and processor.
 7572: 
 7573: @item
 7574: Consequently, the full power of Forth is available in macro definitions.
 7575: E.g., you can perform arbitrarily complex computations, or generate
 7576: different code conditionally or in a loop (e.g., @pxref{Advanced macros
 7577: Tutorial}).  This power is very useful when writing a parser generators
 7578: or other code-generating software.
 7579: 
 7580: @item
 7581: Macros defined using @code{postpone} etc. deal with the language at a
 7582: higher level than strings; name binding happens at macro definition
 7583: time, so you can avoid the pitfalls of name collisions that can happen
 7584: in C macros.  Of course, Forth is a liberal language and also allows to
 7585: shoot yourself in the foot with text-interpreted macros like
 7586: 
 7587: @example
 7588: : [compile-+] s" +" evaluate ; immediate
 7589: @end example
 7590: 
 7591: Apart from binding the name at macro use time, using @code{evaluate}
 7592: also makes your definition @code{state}-smart (@pxref{state-smartness}).
 7593: @end itemize
 7594: 
 7595: You may want the macro to compile a number into a word.  The word to do
 7596: it is @code{literal}, but you have to @code{postpone} it, so its
 7597: compilation semantics take effect when the macro is executed, not when
 7598: it is compiled:
 7599: 
 7600: @example
 7601: : [compile-5] ( -- ) \ compiled code: ( -- n )
 7602:   5 POSTPONE literal ; immediate
 7603: 
 7604: : foo [compile-5] ;
 7605: foo .
 7606: @end example
 7607: 
 7608: You may want to pass parameters to a macro, that the macro should
 7609: compile into the current definition.  If the parameter is a number, then
 7610: you can use @code{postpone literal} (similar for other values).
 7611: 
 7612: If you want to pass a word that is to be compiled, the usual way is to
 7613: pass an execution token and @code{compile,} it:
 7614: 
 7615: @example
 7616: : twice1 ( xt -- ) \ compiled code: ... -- ...
 7617:   dup compile, compile, ;
 7618: 
 7619: : 2+ ( n1 -- n2 )
 7620:   [ ' 1+ twice1 ] ;
 7621: @end example
 7622: 
 7623: doc-compile,
 7624: 
 7625: An alternative available in Gforth, that allows you to pass compile-only
 7626: words as parameters is to use the compilation token (@pxref{Compilation
 7627: token}).  The same example in this technique:
 7628: 
 7629: @example
 7630: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
 7631:   2dup 2>r execute 2r> execute ;
 7632: 
 7633: : 2+ ( n1 -- n2 )
 7634:   [ comp' 1+ twice ] ;
 7635: @end example
 7636: 
 7637: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
 7638: works even if the executed compilation semantics has an effect on the
 7639: data stack.
 7640: 
 7641: You can also define complete definitions with these words; this provides
 7642: an alternative to using @code{does>} (@pxref{User-defined Defining
 7643: Words}).  E.g., instead of
 7644: 
 7645: @example
 7646: : curry+ ( n1 "name" -- )
 7647:     CREATE ,
 7648: DOES> ( n2 -- n1+n2 )
 7649:     @@ + ;
 7650: @end example
 7651: 
 7652: you could define
 7653: 
 7654: @example
 7655: : curry+ ( n1 "name" -- )
 7656:   \ name execution: ( n2 -- n1+n2 )
 7657:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
 7658: 
 7659: -3 curry+ 3-
 7660: see 3-
 7661: @end example
 7662: 
 7663: The sequence @code{>r : r>} is necessary, because @code{:} puts a
 7664: colon-sys on the data stack that makes everything below it unaccessible.
 7665: 
 7666: This way of writing defining words is sometimes more, sometimes less
 7667: convenient than using @code{does>} (@pxref{Advanced does> usage
 7668: example}).  One advantage of this method is that it can be optimized
 7669: better, because the compiler knows that the value compiled with
 7670: @code{literal} is fixed, whereas the data associated with a
 7671: @code{create}d word can be changed.
 7672: 
 7673: @c doc-[compile] !! not properly documented
 7674: 
 7675: @c ----------------------------------------------------------
 7676: @node The Text Interpreter, The Input Stream, Compiling words, Words
 7677: @section  The Text Interpreter
 7678: @cindex interpreter - outer
 7679: @cindex text interpreter
 7680: @cindex outer interpreter
 7681: 
 7682: @c Should we really describe all these ugly details?  IMO the text
 7683: @c interpreter should be much cleaner, but that may not be possible within
 7684: @c ANS Forth. - anton
 7685: @c nac-> I wanted to explain how it works to show how you can exploit
 7686: @c it in your own programs. When I was writing a cross-compiler, figuring out
 7687: @c some of these gory details was very helpful to me. None of the textbooks
 7688: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
 7689: @c seems to positively avoid going into too much detail for some of
 7690: @c the internals.
 7691: 
 7692: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
 7693: @c it is; for the ugly details, I would prefer another place.  I wonder
 7694: @c whether we should have a chapter before "Words" that describes some
 7695: @c basic concepts referred to in words, and a chapter after "Words" that
 7696: @c describes implementation details.
 7697: 
 7698: The text interpreter@footnote{This is an expanded version of the
 7699: material in @ref{Introducing the Text Interpreter}.} is an endless loop
 7700: that processes input from the current input device. It is also called
 7701: the outer interpreter, in contrast to the inner interpreter
 7702: (@pxref{Engine}) which executes the compiled Forth code on interpretive
 7703: implementations.
 7704: 
 7705: @cindex interpret state
 7706: @cindex compile state
 7707: The text interpreter operates in one of two states: @dfn{interpret
 7708: state} and @dfn{compile state}. The current state is defined by the
 7709: aptly-named variable @code{state}.
 7710: 
 7711: This section starts by describing how the text interpreter behaves when
 7712: it is in interpret state, processing input from the user input device --
 7713: the keyboard. This is the mode that a Forth system is in after it starts
 7714: up.
 7715: 
 7716: @cindex input buffer
 7717: @cindex terminal input buffer
 7718: The text interpreter works from an area of memory called the @dfn{input
 7719: buffer}@footnote{When the text interpreter is processing input from the
 7720: keyboard, this area of memory is called the @dfn{terminal input buffer}
 7721: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
 7722: @code{#TIB}.}, which stores your keyboard input when you press the
 7723: @key{RET} key. Starting at the beginning of the input buffer, it skips
 7724: leading spaces (called @dfn{delimiters}) then parses a string (a
 7725: sequence of non-space characters) until it reaches either a space
 7726: character or the end of the buffer. Having parsed a string, it makes two
 7727: attempts to process it:
 7728: 
 7729: @cindex dictionary
 7730: @itemize @bullet
 7731: @item
 7732: It looks for the string in a @dfn{dictionary} of definitions. If the
 7733: string is found, the string names a @dfn{definition} (also known as a
 7734: @dfn{word}) and the dictionary search returns information that allows
 7735: the text interpreter to perform the word's @dfn{interpretation
 7736: semantics}. In most cases, this simply means that the word will be
 7737: executed.
 7738: @item
 7739: If the string is not found in the dictionary, the text interpreter
 7740: attempts to treat it as a number, using the rules described in
 7741: @ref{Number Conversion}. If the string represents a legal number in the
 7742: current radix, the number is pushed onto a parameter stack (the data
 7743: stack for integers, the floating-point stack for floating-point
 7744: numbers).
 7745: @end itemize
 7746: 
 7747: If both attempts fail, or if the word is found in the dictionary but has
 7748: no interpretation semantics@footnote{This happens if the word was
 7749: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
 7750: remainder of the input buffer, issues an error message and waits for
 7751: more input. If one of the attempts succeeds, the text interpreter
 7752: repeats the parsing process until the whole of the input buffer has been
 7753: processed, at which point it prints the status message ``@code{ ok}''
 7754: and waits for more input.
 7755: 
 7756: @c anton: this should be in the input stream subsection (or below it)
 7757: 
 7758: @cindex parse area
 7759: The text interpreter keeps track of its position in the input buffer by
 7760: updating a variable called @code{>IN} (pronounced ``to-in''). The value
 7761: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
 7762: of the input buffer. The region from offset @code{>IN @@} to the end of
 7763: the input buffer is called the @dfn{parse area}@footnote{In other words,
 7764: the text interpreter processes the contents of the input buffer by
 7765: parsing strings from the parse area until the parse area is empty.}.
 7766: This example shows how @code{>IN} changes as the text interpreter parses
 7767: the input buffer:
 7768: 
 7769: @example
 7770: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
 7771:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
 7772: 
 7773: 1 2 3 remaining + remaining . 
 7774: 
 7775: : foo 1 2 3 remaining SWAP remaining ;
 7776: @end example
 7777: 
 7778: @noindent
 7779: The result is:
 7780: 
 7781: @example
 7782: ->+ remaining .<-
 7783: ->.<-5  ok
 7784: 
 7785: ->SWAP remaining ;-<
 7786: ->;<-  ok
 7787: @end example
 7788: 
 7789: @cindex parsing words
 7790: The value of @code{>IN} can also be modified by a word in the input
 7791: buffer that is executed by the text interpreter.  This means that a word
 7792: can ``trick'' the text interpreter into either skipping a section of the
 7793: input buffer@footnote{This is how parsing words work.} or into parsing a
 7794: section twice. For example:
 7795: 
 7796: @example
 7797: : lat ." <<foo>>" ;
 7798: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
 7799: @end example
 7800: 
 7801: @noindent
 7802: When @code{flat} is executed, this output is produced@footnote{Exercise
 7803: for the reader: what would happen if the @code{3} were replaced with
 7804: @code{4}?}:
 7805: 
 7806: @example
 7807: <<bar>><<foo>>
 7808: @end example
 7809: 
 7810: This technique can be used to work around some of the interoperability
 7811: problems of parsing words.  Of course, it's better to avoid parsing
 7812: words where possible.
 7813: 
 7814: @noindent
 7815: Two important notes about the behaviour of the text interpreter:
 7816: 
 7817: @itemize @bullet
 7818: @item
 7819: It processes each input string to completion before parsing additional
 7820: characters from the input buffer.
 7821: @item
 7822: It treats the input buffer as a read-only region (and so must your code).
 7823: @end itemize
 7824: 
 7825: @noindent
 7826: When the text interpreter is in compile state, its behaviour changes in
 7827: these ways:
 7828: 
 7829: @itemize @bullet
 7830: @item
 7831: If a parsed string is found in the dictionary, the text interpreter will
 7832: perform the word's @dfn{compilation semantics}. In most cases, this
 7833: simply means that the execution semantics of the word will be appended
 7834: to the current definition.
 7835: @item
 7836: When a number is encountered, it is compiled into the current definition
 7837: (as a literal) rather than being pushed onto a parameter stack.
 7838: @item
 7839: If an error occurs, @code{state} is modified to put the text interpreter
 7840: back into interpret state.
 7841: @item
 7842: Each time a line is entered from the keyboard, Gforth prints
 7843: ``@code{ compiled}'' rather than `` @code{ok}''.
 7844: @end itemize
 7845: 
 7846: @cindex text interpreter - input sources
 7847: When the text interpreter is using an input device other than the
 7848: keyboard, its behaviour changes in these ways:
 7849: 
 7850: @itemize @bullet
 7851: @item
 7852: When the parse area is empty, the text interpreter attempts to refill
 7853: the input buffer from the input source. When the input source is
 7854: exhausted, the input source is set back to the previous input source.
 7855: @item
 7856: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
 7857: time the parse area is emptied.
 7858: @item
 7859: If an error occurs, the input source is set back to the user input
 7860: device.
 7861: @end itemize
 7862: 
 7863: You can read about this in more detail in @ref{Input Sources}.
 7864: 
 7865: doc->in
 7866: doc-source
 7867: 
 7868: doc-tib
 7869: doc-#tib
 7870: 
 7871: 
 7872: @menu
 7873: * Input Sources::               
 7874: * Number Conversion::           
 7875: * Interpret/Compile states::    
 7876: * Interpreter Directives::      
 7877: @end menu
 7878: 
 7879: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
 7880: @subsection Input Sources
 7881: @cindex input sources
 7882: @cindex text interpreter - input sources
 7883: 
 7884: By default, the text interpreter processes input from the user input
 7885: device (the keyboard) when Forth starts up. The text interpreter can
 7886: process input from any of these sources:
 7887: 
 7888: @itemize @bullet
 7889: @item
 7890: The user input device -- the keyboard.
 7891: @item
 7892: A file, using the words described in @ref{Forth source files}.
 7893: @item
 7894: A block, using the words described in @ref{Blocks}.
 7895: @item
 7896: A text string, using @code{evaluate}.
 7897: @end itemize
 7898: 
 7899: A program can identify the current input device from the values of
 7900: @code{source-id} and @code{blk}.
 7901: 
 7902: 
 7903: doc-source-id
 7904: doc-blk
 7905: 
 7906: doc-save-input
 7907: doc-restore-input
 7908: 
 7909: doc-evaluate
 7910: doc-query
 7911: 
 7912: 
 7913: 
 7914: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
 7915: @subsection Number Conversion
 7916: @cindex number conversion
 7917: @cindex double-cell numbers, input format
 7918: @cindex input format for double-cell numbers
 7919: @cindex single-cell numbers, input format
 7920: @cindex input format for single-cell numbers
 7921: @cindex floating-point numbers, input format
 7922: @cindex input format for floating-point numbers
 7923: 
 7924: This section describes the rules that the text interpreter uses when it
 7925: tries to convert a string into a number.
 7926: 
 7927: Let <digit> represent any character that is a legal digit in the current
 7928: number base@footnote{For example, 0-9 when the number base is decimal or
 7929: 0-9, A-F when the number base is hexadecimal.}.
 7930: 
 7931: Let <decimal digit> represent any character in the range 0-9.
 7932: 
 7933: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
 7934: in the braces (@i{a} or @i{b} or neither).
 7935: 
 7936: Let * represent any number of instances of the previous character
 7937: (including none).
 7938: 
 7939: Let any other character represent itself.
 7940: 
 7941: @noindent
 7942: Now, the conversion rules are:
 7943: 
 7944: @itemize @bullet
 7945: @item
 7946: A string of the form <digit><digit>* is treated as a single-precision
 7947: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
 7948: @item
 7949: A string of the form -<digit><digit>* is treated as a single-precision
 7950: (cell-sized) negative integer, and is represented using 2's-complement
 7951: arithmetic. Examples are -45 -5681 -0
 7952: @item
 7953: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
 7954: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
 7955: (all three of these represent the same number).
 7956: @item
 7957: A string of the form -<digit><digit>*.<digit>* is treated as a
 7958: double-precision (double-cell-sized) negative integer, and is
 7959: represented using 2's-complement arithmetic. Examples are -3465. -3.465
 7960: -34.65 (all three of these represent the same number).
 7961: @item
 7962: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
 7963: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
 7964: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
 7965: number) +12.E-4
 7966: @end itemize
 7967: 
 7968: By default, the number base used for integer number conversion is
 7969: given by the contents of the variable @code{base}.  Note that a lot of
 7970: confusion can result from unexpected values of @code{base}.  If you
 7971: change @code{base} anywhere, make sure to save the old value and
 7972: restore it afterwards; better yet, use @code{base-execute}, which does
 7973: this for you.  In general I recommend keeping @code{base} decimal, and
 7974: using the prefixes described below for the popular non-decimal bases.
 7975: 
 7976: doc-dpl
 7977: doc-base-execute
 7978: doc-base
 7979: doc-hex
 7980: doc-decimal
 7981: 
 7982: @cindex '-prefix for character strings
 7983: @cindex &-prefix for decimal numbers
 7984: @cindex #-prefix for decimal numbers
 7985: @cindex %-prefix for binary numbers
 7986: @cindex $-prefix for hexadecimal numbers
 7987: @cindex 0x-prefix for hexadecimal numbers
 7988: Gforth allows you to override the value of @code{base} by using a
 7989: prefix@footnote{Some Forth implementations provide a similar scheme by
 7990: implementing @code{$} etc. as parsing words that process the subsequent
 7991: number in the input stream and push it onto the stack. For example, see
 7992: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
 7993: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
 7994: is required between the prefix and the number.} before the first digit
 7995: of an (integer) number. The following prefixes are supported:
 7996: 
 7997: @itemize @bullet
 7998: @item
 7999: @code{&} -- decimal
 8000: @item
 8001: @code{#} -- decimal
 8002: @item
 8003: @code{%} -- binary
 8004: @item
 8005: @code{$} -- hexadecimal
 8006: @item
 8007: @code{0x} -- hexadecimal, if base<33.
 8008: @item
 8009: @code{'} -- numeric value (e.g., ASCII code) of next character; an
 8010: optional @code{'} may be present after the character.
 8011: @end itemize
 8012: 
 8013: Here are some examples, with the equivalent decimal number shown after
 8014: in braces:
 8015: 
 8016: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
 8017: 'A (65),
 8018: -'a' (-97),
 8019: &905 (905), $abc (2478), $ABC (2478).
 8020: 
 8021: @cindex number conversion - traps for the unwary
 8022: @noindent
 8023: Number conversion has a number of traps for the unwary:
 8024: 
 8025: @itemize @bullet
 8026: @item
 8027: You cannot determine the current number base using the code sequence
 8028: @code{base @@ .} -- the number base is always 10 in the current number
 8029: base. Instead, use something like @code{base @@ dec.}
 8030: @item
 8031: If the number base is set to a value greater than 14 (for example,
 8032: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
 8033: it to be intepreted as either a single-precision integer or a
 8034: floating-point number (Gforth treats it as an integer). The ambiguity
 8035: can be resolved by explicitly stating the sign of the mantissa and/or
 8036: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
 8037: ambiguity arises; either representation will be treated as a
 8038: floating-point number.
 8039: @item
 8040: There is a word @code{bin} but it does @i{not} set the number base!
 8041: It is used to specify file types.
 8042: @item
 8043: ANS Forth requires the @code{.} of a double-precision number to be the
 8044: final character in the string.  Gforth allows the @code{.} to be
 8045: anywhere after the first digit.
 8046: @item
 8047: The number conversion process does not check for overflow.
 8048: @item
 8049: In an ANS Forth program @code{base} is required to be decimal when
 8050: converting floating-point numbers.  In Gforth, number conversion to
 8051: floating-point numbers always uses base &10, irrespective of the value
 8052: of @code{base}.
 8053: @end itemize
 8054: 
 8055: You can read numbers into your programs with the words described in
 8056: @ref{Line input and conversion}.
 8057: 
 8058: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
 8059: @subsection Interpret/Compile states
 8060: @cindex Interpret/Compile states
 8061: 
 8062: A standard program is not permitted to change @code{state}
 8063: explicitly. However, it can change @code{state} implicitly, using the
 8064: words @code{[} and @code{]}. When @code{[} is executed it switches
 8065: @code{state} to interpret state, and therefore the text interpreter
 8066: starts interpreting. When @code{]} is executed it switches @code{state}
 8067: to compile state and therefore the text interpreter starts
 8068: compiling. The most common usage for these words is for switching into
 8069: interpret state and back from within a colon definition; this technique
 8070: can be used to compile a literal (for an example, @pxref{Literals}) or
 8071: for conditional compilation (for an example, @pxref{Interpreter
 8072: Directives}).
 8073: 
 8074: 
 8075: @c This is a bad example: It's non-standard, and it's not necessary.
 8076: @c However, I can't think of a good example for switching into compile
 8077: @c state when there is no current word (@code{state}-smart words are not a
 8078: @c good reason).  So maybe we should use an example for switching into
 8079: @c interpret @code{state} in a colon def. - anton
 8080: @c nac-> I agree. I started out by putting in the example, then realised
 8081: @c that it was non-ANS, so wrote more words around it. I hope this
 8082: @c re-written version is acceptable to you. I do want to keep the example
 8083: @c as it is helpful for showing what is and what is not portable, particularly
 8084: @c where it outlaws a style in common use.
 8085: 
 8086: @c anton: it's more important to show what's portable.  After we have done
 8087: @c that, we can also show what's not.  In any case, I have written a
 8088: @c section Compiling Words which also deals with [ ].
 8089: 
 8090: @c  !! The following example does not work in Gforth 0.5.9 or later.
 8091: 
 8092: @c  @code{[} and @code{]} also give you the ability to switch into compile
 8093: @c  state and back, but we cannot think of any useful Standard application
 8094: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
 8095: 
 8096: @c  @example
 8097: @c  : AA ." this is A" ;
 8098: @c  : BB ." this is B" ;
 8099: @c  : CC ." this is C" ;
 8100: 
 8101: @c  create table ] aa bb cc [
 8102: 
 8103: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
 8104: @c    cells table + @@ execute ;
 8105: @c  @end example
 8106: 
 8107: @c  This example builds a jump table; @code{0 go} will display ``@code{this
 8108: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
 8109: @c  defining @code{table} like this:
 8110: 
 8111: @c  @example
 8112: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
 8113: @c  @end example
 8114: 
 8115: @c  The problem with this code is that the definition of @code{table} is not
 8116: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
 8117: @c  @i{may} work on systems where code space and data space co-incide, the
 8118: @c  Standard only allows data space to be assigned for a @code{CREATE}d
 8119: @c  word. In addition, the Standard only allows @code{@@} to access data
 8120: @c  space, whilst this example is using it to access code space. The only
 8121: @c  portable, Standard way to build this table is to build it in data space,
 8122: @c  like this:
 8123: 
 8124: @c  @example
 8125: @c  create table ' aa , ' bb , ' cc ,
 8126: @c  @end example
 8127: 
 8128: @c  doc-state
 8129: 
 8130: 
 8131: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
 8132: @subsection Interpreter Directives
 8133: @cindex interpreter directives
 8134: @cindex conditional compilation
 8135: 
 8136: These words are usually used in interpret state; typically to control
 8137: which parts of a source file are processed by the text
 8138: interpreter. There are only a few ANS Forth Standard words, but Gforth
 8139: supplements these with a rich set of immediate control structure words
 8140: to compensate for the fact that the non-immediate versions can only be
 8141: used in compile state (@pxref{Control Structures}). Typical usages:
 8142: 
 8143: @example
 8144: FALSE Constant HAVE-ASSEMBLER
 8145: .
 8146: .
 8147: HAVE-ASSEMBLER [IF]
 8148: : ASSEMBLER-FEATURE
 8149:   ...
 8150: ;
 8151: [ENDIF]
 8152: .
 8153: .
 8154: : SEE
 8155:   ... \ general-purpose SEE code
 8156:   [ HAVE-ASSEMBLER [IF] ]
 8157:   ... \ assembler-specific SEE code
 8158:   [ [ENDIF] ]
 8159: ;
 8160: @end example
 8161: 
 8162: 
 8163: doc-[IF]
 8164: doc-[ELSE]
 8165: doc-[THEN]
 8166: doc-[ENDIF]
 8167: 
 8168: doc-[IFDEF]
 8169: doc-[IFUNDEF]
 8170: 
 8171: doc-[?DO]
 8172: doc-[DO]
 8173: doc-[FOR]
 8174: doc-[LOOP]
 8175: doc-[+LOOP]
 8176: doc-[NEXT]
 8177: 
 8178: doc-[BEGIN]
 8179: doc-[UNTIL]
 8180: doc-[AGAIN]
 8181: doc-[WHILE]
 8182: doc-[REPEAT]
 8183: 
 8184: 
 8185: @c -------------------------------------------------------------
 8186: @node The Input Stream, Word Lists, The Text Interpreter, Words
 8187: @section The Input Stream
 8188: @cindex input stream
 8189: 
 8190: @c !! integrate this better with the "Text Interpreter" section
 8191: The text interpreter reads from the input stream, which can come from
 8192: several sources (@pxref{Input Sources}).  Some words, in particular
 8193: defining words, but also words like @code{'}, read parameters from the
 8194: input stream instead of from the stack.
 8195: 
 8196: Such words are called parsing words, because they parse the input
 8197: stream.  Parsing words are hard to use in other words, because it is
 8198: hard to pass program-generated parameters through the input stream.
 8199: They also usually have an unintuitive combination of interpretation and
 8200: compilation semantics when implemented naively, leading to various
 8201: approaches that try to produce a more intuitive behaviour
 8202: (@pxref{Combined words}).
 8203: 
 8204: It should be obvious by now that parsing words are a bad idea.  If you
 8205: want to implement a parsing word for convenience, also provide a factor
 8206: of the word that does not parse, but takes the parameters on the stack.
 8207: To implement the parsing word on top if it, you can use the following
 8208: words:
 8209: 
 8210: @c anton: these belong in the input stream section
 8211: doc-parse
 8212: doc-parse-name
 8213: doc-parse-word
 8214: doc-name
 8215: doc-word
 8216: doc-refill
 8217: 
 8218: Conversely, if you have the bad luck (or lack of foresight) to have to
 8219: deal with parsing words without having such factors, how do you pass a
 8220: string that is not in the input stream to it?
 8221: 
 8222: doc-execute-parsing
 8223: 
 8224: A definition of this word in ANS Forth is provided in
 8225: @file{compat/execute-parsing.fs}.
 8226: 
 8227: If you want to run a parsing word on a file, the following word should
 8228: help:
 8229: 
 8230: doc-execute-parsing-file
 8231: 
 8232: @c -------------------------------------------------------------
 8233: @node Word Lists, Environmental Queries, The Input Stream, Words
 8234: @section Word Lists
 8235: @cindex word lists
 8236: @cindex header space
 8237: 
 8238: A wordlist is a list of named words; you can add new words and look up
 8239: words by name (and you can remove words in a restricted way with
 8240: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
 8241: 
 8242: @cindex search order stack
 8243: The text interpreter searches the wordlists present in the search order
 8244: (a stack of wordlists), from the top to the bottom.  Within each
 8245: wordlist, the search starts conceptually at the newest word; i.e., if
 8246: two words in a wordlist have the same name, the newer word is found.
 8247: 
 8248: @cindex compilation word list
 8249: New words are added to the @dfn{compilation wordlist} (aka current
 8250: wordlist).
 8251: 
 8252: @cindex wid
 8253: A word list is identified by a cell-sized word list identifier (@i{wid})
 8254: in much the same way as a file is identified by a file handle. The
 8255: numerical value of the wid has no (portable) meaning, and might change
 8256: from session to session.
 8257: 
 8258: The ANS Forth ``Search order'' word set is intended to provide a set of
 8259: low-level tools that allow various different schemes to be
 8260: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
 8261: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
 8262: Forth.
 8263: 
 8264: @comment TODO: locals section refers to here, saying that every word list (aka
 8265: @comment vocabulary) has its own methods for searching etc. Need to document that.
 8266: @c anton: but better in a separate subsection on wordlist internals
 8267: 
 8268: @comment TODO: document markers, reveal, tables, mappedwordlist
 8269: 
 8270: @comment the gforthman- prefix is used to pick out the true definition of a
 8271: @comment word from the source files, rather than some alias.
 8272: 
 8273: doc-forth-wordlist
 8274: doc-definitions
 8275: doc-get-current
 8276: doc-set-current
 8277: doc-get-order
 8278: doc-set-order
 8279: doc-wordlist
 8280: doc-table
 8281: doc->order
 8282: doc-previous
 8283: doc-also
 8284: doc-forth
 8285: doc-only
 8286: doc-order
 8287: 
 8288: doc-find
 8289: doc-search-wordlist
 8290: 
 8291: doc-words
 8292: doc-vlist
 8293: @c doc-words-deferred
 8294: 
 8295: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
 8296: doc-root
 8297: doc-vocabulary
 8298: doc-seal
 8299: doc-vocs
 8300: doc-current
 8301: doc-context
 8302: 
 8303: 
 8304: @menu
 8305: * Vocabularies::                
 8306: * Why use word lists?::         
 8307: * Word list example::           
 8308: @end menu
 8309: 
 8310: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
 8311: @subsection Vocabularies
 8312: @cindex Vocabularies, detailed explanation
 8313: 
 8314: Here is an example of creating and using a new wordlist using ANS
 8315: Forth words:
 8316: 
 8317: @example
 8318: wordlist constant my-new-words-wordlist
 8319: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
 8320: 
 8321: \ add it to the search order
 8322: also my-new-words
 8323: 
 8324: \ alternatively, add it to the search order and make it
 8325: \ the compilation word list
 8326: also my-new-words definitions
 8327: \ type "order" to see the problem
 8328: @end example
 8329: 
 8330: The problem with this example is that @code{order} has no way to
 8331: associate the name @code{my-new-words} with the wid of the word list (in
 8332: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
 8333: that has no associated name). There is no Standard way of associating a
 8334: name with a wid.
 8335: 
 8336: In Gforth, this example can be re-coded using @code{vocabulary}, which
 8337: associates a name with a wid:
 8338: 
 8339: @example
 8340: vocabulary my-new-words
 8341: 
 8342: \ add it to the search order
 8343: also my-new-words
 8344: 
 8345: \ alternatively, add it to the search order and make it
 8346: \ the compilation word list
 8347: my-new-words definitions
 8348: \ type "order" to see that the problem is solved
 8349: @end example
 8350: 
 8351: 
 8352: @node Why use word lists?, Word list example, Vocabularies, Word Lists
 8353: @subsection Why use word lists?
 8354: @cindex word lists - why use them?
 8355: 
 8356: Here are some reasons why people use wordlists:
 8357: 
 8358: @itemize @bullet
 8359: 
 8360: @c anton: Gforth's hashing implementation makes the search speed
 8361: @c independent from the number of words.  But it is linear with the number
 8362: @c of wordlists that have to be searched, so in effect using more wordlists
 8363: @c actually slows down compilation.
 8364: 
 8365: @c @item
 8366: @c To improve compilation speed by reducing the number of header space
 8367: @c entries that must be searched. This is achieved by creating a new
 8368: @c word list that contains all of the definitions that are used in the
 8369: @c definition of a Forth system but which would not usually be used by
 8370: @c programs running on that system. That word list would be on the search
 8371: @c list when the Forth system was compiled but would be removed from the
 8372: @c search list for normal operation. This can be a useful technique for
 8373: @c low-performance systems (for example, 8-bit processors in embedded
 8374: @c systems) but is unlikely to be necessary in high-performance desktop
 8375: @c systems.
 8376: 
 8377: @item
 8378: To prevent a set of words from being used outside the context in which
 8379: they are valid. Two classic examples of this are an integrated editor
 8380: (all of the edit commands are defined in a separate word list; the
 8381: search order is set to the editor word list when the editor is invoked;
 8382: the old search order is restored when the editor is terminated) and an
 8383: integrated assembler (the op-codes for the machine are defined in a
 8384: separate word list which is used when a @code{CODE} word is defined).
 8385: 
 8386: @item
 8387: To organize the words of an application or library into a user-visible
 8388: set (in @code{forth-wordlist} or some other common wordlist) and a set
 8389: of helper words used just for the implementation (hidden in a separate
 8390: wordlist).  This keeps @code{words}' output smaller, separates
 8391: implementation and interface, and reduces the chance of name conflicts
 8392: within the common wordlist.
 8393: 
 8394: @item
 8395: To prevent a name-space clash between multiple definitions with the same
 8396: name. For example, when building a cross-compiler you might have a word
 8397: @code{IF} that generates conditional code for your target system. By
 8398: placing this definition in a different word list you can control whether
 8399: the host system's @code{IF} or the target system's @code{IF} get used in
 8400: any particular context by controlling the order of the word lists on the
 8401: search order stack.
 8402: 
 8403: @end itemize
 8404: 
 8405: The downsides of using wordlists are:
 8406: 
 8407: @itemize
 8408: 
 8409: @item
 8410: Debugging becomes more cumbersome.
 8411: 
 8412: @item
 8413: Name conflicts worked around with wordlists are still there, and you
 8414: have to arrange the search order carefully to get the desired results;
 8415: if you forget to do that, you get hard-to-find errors (as in any case
 8416: where you read the code differently from the compiler; @code{see} can
 8417: help seeing which of several possible words the name resolves to in such
 8418: cases).  @code{See} displays just the name of the words, not what
 8419: wordlist they belong to, so it might be misleading.  Using unique names
 8420: is a better approach to avoid name conflicts.
 8421: 
 8422: @item
 8423: You have to explicitly undo any changes to the search order.  In many
 8424: cases it would be more convenient if this happened implicitly.  Gforth
 8425: currently does not provide such a feature, but it may do so in the
 8426: future.
 8427: @end itemize
 8428: 
 8429: 
 8430: @node Word list example,  , Why use word lists?, Word Lists
 8431: @subsection Word list example
 8432: @cindex word lists - example
 8433: 
 8434: The following example is from the
 8435: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
 8436: garbage collector} and uses wordlists to separate public words from
 8437: helper words:
 8438: 
 8439: @example
 8440: get-current ( wid )
 8441: vocabulary garbage-collector also garbage-collector definitions
 8442: ... \ define helper words
 8443: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
 8444: ... \ define the public (i.e., API) words
 8445:     \ they can refer to the helper words
 8446: previous \ restore original search order (helper words become invisible)
 8447: @end example
 8448: 
 8449: @c -------------------------------------------------------------
 8450: @node Environmental Queries, Files, Word Lists, Words
 8451: @section Environmental Queries
 8452: @cindex environmental queries
 8453: 
 8454: ANS Forth introduced the idea of ``environmental queries'' as a way
 8455: for a program running on a system to determine certain characteristics of the system.
 8456: The Standard specifies a number of strings that might be recognised by a system.
 8457: 
 8458: The Standard requires that the header space used for environmental queries
 8459: be distinct from the header space used for definitions.
 8460: 
 8461: Typically, environmental queries are supported by creating a set of
 8462: definitions in a word list that is @i{only} used during environmental
 8463: queries; that is what Gforth does. There is no Standard way of adding
 8464: definitions to the set of recognised environmental queries, but any
 8465: implementation that supports the loading of optional word sets must have
 8466: some mechanism for doing this (after loading the word set, the
 8467: associated environmental query string must return @code{true}). In
 8468: Gforth, the word list used to honour environmental queries can be
 8469: manipulated just like any other word list.
 8470: 
 8471: 
 8472: doc-environment?
 8473: doc-environment-wordlist
 8474: 
 8475: doc-gforth
 8476: doc-os-class
 8477: 
 8478: 
 8479: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
 8480: returning two items on the stack, querying it using @code{environment?}
 8481: will return an additional item; the @code{true} flag that shows that the
 8482: string was recognised.
 8483: 
 8484: @comment TODO Document the standard strings or note where they are documented herein
 8485: 
 8486: Here are some examples of using environmental queries:
 8487: 
 8488: @example
 8489: s" address-unit-bits" environment? 0=
 8490: [IF]
 8491:      cr .( environmental attribute address-units-bits unknown... ) cr
 8492: [ELSE]
 8493:      drop \ ensure balanced stack effect
 8494: [THEN]
 8495: 
 8496: \ this might occur in the prelude of a standard program that uses THROW
 8497: s" exception" environment? [IF]
 8498:    0= [IF]
 8499:       : throw abort" exception thrown" ;
 8500:    [THEN]
 8501: [ELSE] \ we don't know, so make sure
 8502:    : throw abort" exception thrown" ;
 8503: [THEN]
 8504: 
 8505: s" gforth" environment? [IF] .( Gforth version ) TYPE
 8506:                         [ELSE] .( Not Gforth..) [THEN]
 8507: 
 8508: \ a program using v*
 8509: s" gforth" environment? [IF]
 8510:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
 8511:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8512:      >r swap 2swap swap 0e r> 0 ?DO
 8513:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
 8514:      LOOP
 8515:      2drop 2drop ; 
 8516:   [THEN]
 8517: [ELSE] \ 
 8518:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
 8519:   ...
 8520: [THEN]
 8521: @end example
 8522: 
 8523: Here is an example of adding a definition to the environment word list:
 8524: 
 8525: @example
 8526: get-current environment-wordlist set-current
 8527: true constant block
 8528: true constant block-ext
 8529: set-current
 8530: @end example
 8531: 
 8532: You can see what definitions are in the environment word list like this:
 8533: 
 8534: @example
 8535: environment-wordlist >order words previous
 8536: @end example
 8537: 
 8538: 
 8539: @c -------------------------------------------------------------
 8540: @node Files, Blocks, Environmental Queries, Words
 8541: @section Files
 8542: @cindex files
 8543: @cindex I/O - file-handling
 8544: 
 8545: Gforth provides facilities for accessing files that are stored in the
 8546: host operating system's file-system. Files that are processed by Gforth
 8547: can be divided into two categories:
 8548: 
 8549: @itemize @bullet
 8550: @item
 8551: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
 8552: @item
 8553: Files that are processed by some other program (@dfn{general files}).
 8554: @end itemize
 8555: 
 8556: @menu
 8557: * Forth source files::          
 8558: * General files::               
 8559: * Redirection::                 
 8560: * Search Paths::                
 8561: @end menu
 8562: 
 8563: @c -------------------------------------------------------------
 8564: @node Forth source files, General files, Files, Files
 8565: @subsection Forth source files
 8566: @cindex including files
 8567: @cindex Forth source files
 8568: 
 8569: The simplest way to interpret the contents of a file is to use one of
 8570: these two formats:
 8571: 
 8572: @example
 8573: include mysource.fs
 8574: s" mysource.fs" included
 8575: @end example
 8576: 
 8577: You usually want to include a file only if it is not included already
 8578: (by, say, another source file). In that case, you can use one of these
 8579: three formats:
 8580: 
 8581: @example
 8582: require mysource.fs
 8583: needs mysource.fs
 8584: s" mysource.fs" required
 8585: @end example
 8586: 
 8587: @cindex stack effect of included files
 8588: @cindex including files, stack effect
 8589: It is good practice to write your source files such that interpreting them
 8590: does not change the stack. Source files designed in this way can be used with
 8591: @code{required} and friends without complications. For example:
 8592: 
 8593: @example
 8594: 1024 require foo.fs drop
 8595: @end example
 8596: 
 8597: Here you want to pass the argument 1024 (e.g., a buffer size) to
 8598: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
 8599: ), which allows its use with @code{require}.  Of course with such
 8600: parameters to required files, you have to ensure that the first
 8601: @code{require} fits for all uses (i.e., @code{require} it early in the
 8602: master load file).
 8603: 
 8604: doc-include-file
 8605: doc-included
 8606: doc-included?
 8607: doc-include
 8608: doc-required
 8609: doc-require
 8610: doc-needs
 8611: @c doc-init-included-files @c internal
 8612: doc-sourcefilename
 8613: doc-sourceline#
 8614: 
 8615: A definition in ANS Forth for @code{required} is provided in
 8616: @file{compat/required.fs}.
 8617: 
 8618: @c -------------------------------------------------------------
 8619: @node General files, Redirection, Forth source files, Files
 8620: @subsection General files
 8621: @cindex general files
 8622: @cindex file-handling
 8623: 
 8624: Files are opened/created by name and type. The following file access
 8625: methods (FAMs) are recognised:
 8626: 
 8627: @cindex fam (file access method)
 8628: doc-r/o
 8629: doc-r/w
 8630: doc-w/o
 8631: doc-bin
 8632: 
 8633: 
 8634: When a file is opened/created, it returns a file identifier,
 8635: @i{wfileid} that is used for all other file commands. All file
 8636: commands also return a status value, @i{wior}, that is 0 for a
 8637: successful operation and an implementation-defined non-zero value in the
 8638: case of an error.
 8639: 
 8640: 
 8641: doc-open-file
 8642: doc-create-file
 8643: 
 8644: doc-close-file
 8645: doc-delete-file
 8646: doc-rename-file
 8647: doc-read-file
 8648: doc-read-line
 8649: doc-key-file
 8650: doc-key?-file
 8651: doc-write-file
 8652: doc-write-line
 8653: doc-emit-file
 8654: doc-flush-file
 8655: 
 8656: doc-file-status
 8657: doc-file-position
 8658: doc-reposition-file
 8659: doc-file-size
 8660: doc-resize-file
 8661: 
 8662: doc-slurp-file
 8663: doc-slurp-fid
 8664: doc-stdin
 8665: doc-stdout
 8666: doc-stderr
 8667: 
 8668: @c ---------------------------------------------------------
 8669: @node Redirection, Search Paths, General files, Files
 8670: @subsection Redirection
 8671: @cindex Redirection
 8672: @cindex Input Redirection
 8673: @cindex Output Redirection
 8674: 
 8675: You can redirect the output of @code{type} and @code{emit} and all the
 8676: words that use them (all output words that don't have an explicit
 8677: target file) to an arbitrary file with the @code{outfile-execute},
 8678: used like this:
 8679: 
 8680: @example
 8681: : some-warning ( n -- )
 8682:     cr ." warning# " . ;
 8683: 
 8684: : print-some-warning ( n -- )
 8685:     ['] some-warning stderr outfile-execute ;
 8686: @end example
 8687: 
 8688: After @code{some-warning} is executed, the original output direction
 8689: is restored; this construct is safe against exceptions.  Similarly,
 8690: there is @code{infile-execute} for redirecting the input of @code{key}
 8691: and its users (any input word that does not take a file explicitly).
 8692: 
 8693: doc-outfile-execute
 8694: doc-infile-execute
 8695: 
 8696: If you do not want to redirect the input or output to a file, you can
 8697: also make use of the fact that @code{key}, @code{emit} and @code{type}
 8698: are deferred words (@pxref{Deferred Words}).  However, in that case
 8699: you have to worry about the restoration and the protection against
 8700: exceptions yourself; also, note that for redirecting the output in
 8701: this way, you have to redirect both @code{emit} and @code{type}.
 8702: 
 8703: @c ---------------------------------------------------------
 8704: @node Search Paths,  , Redirection, Files
 8705: @subsection Search Paths
 8706: @cindex path for @code{included}
 8707: @cindex file search path
 8708: @cindex @code{include} search path
 8709: @cindex search path for files
 8710: 
 8711: If you specify an absolute filename (i.e., a filename starting with
 8712: @file{/} or @file{~}, or with @file{:} in the second position (as in
 8713: @samp{C:...})) for @code{included} and friends, that file is included
 8714: just as you would expect.
 8715: 
 8716: If the filename starts with @file{./}, this refers to the directory that
 8717: the present file was @code{included} from.  This allows files to include
 8718: other files relative to their own position (irrespective of the current
 8719: working directory or the absolute position).  This feature is essential
 8720: for libraries consisting of several files, where a file may include
 8721: other files from the library.  It corresponds to @code{#include "..."}
 8722: in C. If the current input source is not a file, @file{.} refers to the
 8723: directory of the innermost file being included, or, if there is no file
 8724: being included, to the current working directory.
 8725: 
 8726: For relative filenames (not starting with @file{./}), Gforth uses a
 8727: search path similar to Forth's search order (@pxref{Word Lists}). It
 8728: tries to find the given filename in the directories present in the path,
 8729: and includes the first one it finds. There are separate search paths for
 8730: Forth source files and general files.  If the search path contains the
 8731: directory @file{.}, this refers to the directory of the current file, or
 8732: the working directory, as if the file had been specified with @file{./}.
 8733: 
 8734: Use @file{~+} to refer to the current working directory (as in the
 8735: @code{bash}).
 8736: 
 8737: @c anton: fold the following subsubsections into this subsection?
 8738: 
 8739: @menu
 8740: * Source Search Paths::         
 8741: * General Search Paths::        
 8742: @end menu
 8743: 
 8744: @c ---------------------------------------------------------
 8745: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
 8746: @subsubsection Source Search Paths
 8747: @cindex search path control, source files
 8748: 
 8749: The search path is initialized when you start Gforth (@pxref{Invoking
 8750: Gforth}). You can display it and change it using @code{fpath} in
 8751: combination with the general path handling words.
 8752: 
 8753: doc-fpath
 8754: @c the functionality of the following words is easily available through
 8755: @c   fpath and the general path words.  The may go away.
 8756: @c doc-.fpath
 8757: @c doc-fpath+
 8758: @c doc-fpath=
 8759: @c doc-open-fpath-file
 8760: 
 8761: @noindent
 8762: Here is an example of using @code{fpath} and @code{require}:
 8763: 
 8764: @example
 8765: fpath path= /usr/lib/forth/|./
 8766: require timer.fs
 8767: @end example
 8768: 
 8769: 
 8770: @c ---------------------------------------------------------
 8771: @node General Search Paths,  , Source Search Paths, Search Paths
 8772: @subsubsection General Search Paths
 8773: @cindex search path control, source files
 8774: 
 8775: Your application may need to search files in several directories, like
 8776: @code{included} does. To facilitate this, Gforth allows you to define
 8777: and use your own search paths, by providing generic equivalents of the
 8778: Forth search path words:
 8779: 
 8780: doc-open-path-file
 8781: doc-path-allot
 8782: doc-clear-path
 8783: doc-also-path
 8784: doc-.path
 8785: doc-path+
 8786: doc-path=
 8787: 
 8788: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
 8789: 
 8790: Here's an example of creating an empty search path:
 8791: @c
 8792: @example
 8793: create mypath 500 path-allot \ maximum length 500 chars (is checked)
 8794: @end example
 8795: 
 8796: @c -------------------------------------------------------------
 8797: @node Blocks, Other I/O, Files, Words
 8798: @section Blocks
 8799: @cindex I/O - blocks
 8800: @cindex blocks
 8801: 
 8802: When you run Gforth on a modern desk-top computer, it runs under the
 8803: control of an operating system which provides certain services.  One of
 8804: these services is @var{file services}, which allows Forth source code
 8805: and data to be stored in files and read into Gforth (@pxref{Files}).
 8806: 
 8807: Traditionally, Forth has been an important programming language on
 8808: systems where it has interfaced directly to the underlying hardware with
 8809: no intervening operating system. Forth provides a mechanism, called
 8810: @dfn{blocks}, for accessing mass storage on such systems.
 8811: 
 8812: A block is a 1024-byte data area, which can be used to hold data or
 8813: Forth source code. No structure is imposed on the contents of the
 8814: block. A block is identified by its number; blocks are numbered
 8815: contiguously from 1 to an implementation-defined maximum.
 8816: 
 8817: A typical system that used blocks but no operating system might use a
 8818: single floppy-disk drive for mass storage, with the disks formatted to
 8819: provide 256-byte sectors. Blocks would be implemented by assigning the
 8820: first four sectors of the disk to block 1, the second four sectors to
 8821: block 2 and so on, up to the limit of the capacity of the disk. The disk
 8822: would not contain any file system information, just the set of blocks.
 8823: 
 8824: @cindex blocks file
 8825: On systems that do provide file services, blocks are typically
 8826: implemented by storing a sequence of blocks within a single @dfn{blocks
 8827: file}.  The size of the blocks file will be an exact multiple of 1024
 8828: bytes, corresponding to the number of blocks it contains. This is the
 8829: mechanism that Gforth uses.
 8830: 
 8831: @cindex @file{blocks.fb}
 8832: Only one blocks file can be open at a time. If you use block words without
 8833: having specified a blocks file, Gforth defaults to the blocks file
 8834: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
 8835: locate a blocks file (@pxref{Source Search Paths}).
 8836: 
 8837: @cindex block buffers
 8838: When you read and write blocks under program control, Gforth uses a
 8839: number of @dfn{block buffers} as intermediate storage. These buffers are
 8840: not used when you use @code{load} to interpret the contents of a block.
 8841: 
 8842: The behaviour of the block buffers is analagous to that of a cache.
 8843: Each block buffer has three states:
 8844: 
 8845: @itemize @bullet
 8846: @item
 8847: Unassigned
 8848: @item
 8849: Assigned-clean
 8850: @item
 8851: Assigned-dirty
 8852: @end itemize
 8853: 
 8854: Initially, all block buffers are @i{unassigned}. In order to access a
 8855: block, the block (specified by its block number) must be assigned to a
 8856: block buffer.
 8857: 
 8858: The assignment of a block to a block buffer is performed by @code{block}
 8859: or @code{buffer}. Use @code{block} when you wish to modify the existing
 8860: contents of a block. Use @code{buffer} when you don't care about the
 8861: existing contents of the block@footnote{The ANS Forth definition of
 8862: @code{buffer} is intended not to cause disk I/O; if the data associated
 8863: with the particular block is already stored in a block buffer due to an
 8864: earlier @code{block} command, @code{buffer} will return that block
 8865: buffer and the existing contents of the block will be
 8866: available. Otherwise, @code{buffer} will simply assign a new, empty
 8867: block buffer for the block.}.
 8868: 
 8869: Once a block has been assigned to a block buffer using @code{block} or
 8870: @code{buffer}, that block buffer becomes the @i{current block
 8871: buffer}. Data may only be manipulated (read or written) within the
 8872: current block buffer.
 8873: 
 8874: When the contents of the current block buffer has been modified it is
 8875: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
 8876: either abandon the changes (by doing nothing) or mark the block as
 8877: changed (assigned-dirty), using @code{update}. Using @code{update} does
 8878: not change the blocks file; it simply changes a block buffer's state to
 8879: @i{assigned-dirty}.  The block will be written implicitly when it's
 8880: buffer is needed for another block, or explicitly by @code{flush} or
 8881: @code{save-buffers}.
 8882: 
 8883: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
 8884: blocks file on disk. Leaving Gforth with @code{bye} also performs a
 8885: @code{flush}.
 8886: 
 8887: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
 8888: algorithm to assign a block buffer to a block. That means that any
 8889: particular block can only be assigned to one specific block buffer,
 8890: called (for the particular operation) the @i{victim buffer}. If the
 8891: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
 8892: the new block immediately. If it is @i{assigned-dirty} its current
 8893: contents are written back to the blocks file on disk before it is
 8894: allocated to the new block.
 8895: 
 8896: Although no structure is imposed on the contents of a block, it is
 8897: traditional to display the contents as 16 lines each of 64 characters.  A
 8898: block provides a single, continuous stream of input (for example, it
 8899: acts as a single parse area) -- there are no end-of-line characters
 8900: within a block, and no end-of-file character at the end of a
 8901: block. There are two consequences of this:
 8902: 
 8903: @itemize @bullet
 8904: @item
 8905: The last character of one line wraps straight into the first character
 8906: of the following line
 8907: @item
 8908: The word @code{\} -- comment to end of line -- requires special
 8909: treatment; in the context of a block it causes all characters until the
 8910: end of the current 64-character ``line'' to be ignored.
 8911: @end itemize
 8912: 
 8913: In Gforth, when you use @code{block} with a non-existent block number,
 8914: the current blocks file will be extended to the appropriate size and the
 8915: block buffer will be initialised with spaces.
 8916: 
 8917: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
 8918: for details) but doesn't encourage the use of blocks; the mechanism is
 8919: only provided for backward compatibility -- ANS Forth requires blocks to
 8920: be available when files are.
 8921: 
 8922: Common techniques that are used when working with blocks include:
 8923: 
 8924: @itemize @bullet
 8925: @item
 8926: A screen editor that allows you to edit blocks without leaving the Forth
 8927: environment.
 8928: @item
 8929: Shadow screens; where every code block has an associated block
 8930: containing comments (for example: code in odd block numbers, comments in
 8931: even block numbers). Typically, the block editor provides a convenient
 8932: mechanism to toggle between code and comments.
 8933: @item
 8934: Load blocks; a single block (typically block 1) contains a number of
 8935: @code{thru} commands which @code{load} the whole of the application.
 8936: @end itemize
 8937: 
 8938: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
 8939: integrated into a Forth programming environment.
 8940: 
 8941: @comment TODO what about errors on open-blocks?
 8942: 
 8943: doc-open-blocks
 8944: doc-use
 8945: doc-block-offset
 8946: doc-get-block-fid
 8947: doc-block-position
 8948: 
 8949: doc-list
 8950: doc-scr
 8951: 
 8952: doc-block
 8953: doc-buffer
 8954: 
 8955: doc-empty-buffers
 8956: doc-empty-buffer
 8957: doc-update
 8958: doc-updated?
 8959: doc-save-buffers
 8960: doc-save-buffer
 8961: doc-flush
 8962: 
 8963: doc-load
 8964: doc-thru
 8965: doc-+load
 8966: doc-+thru
 8967: doc---gforthman--->
 8968: doc-block-included
 8969: 
 8970: 
 8971: @c -------------------------------------------------------------
 8972: @node Other I/O, OS command line arguments, Blocks, Words
 8973: @section Other I/O
 8974: @cindex I/O - keyboard and display
 8975: 
 8976: @menu
 8977: * Simple numeric output::       Predefined formats
 8978: * Formatted numeric output::    Formatted (pictured) output
 8979: * String Formats::              How Forth stores strings in memory
 8980: * Displaying characters and strings::  Other stuff
 8981: * String words::                Gforth's little string library
 8982: * Terminal output::             Cursor positioning etc.
 8983: * Single-key input::            
 8984: * Line input and conversion::   
 8985: * Pipes::                       How to create your own pipes
 8986: * Xchars and Unicode::          Non-ASCII characters
 8987: @end menu
 8988: 
 8989: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
 8990: @subsection Simple numeric output
 8991: @cindex numeric output - simple/free-format
 8992: 
 8993: The simplest output functions are those that display numbers from the
 8994: data or floating-point stacks. Floating-point output is always displayed
 8995: using base 10. Numbers displayed from the data stack use the value stored
 8996: in @code{base}.
 8997: 
 8998: 
 8999: doc-.
 9000: doc-dec.
 9001: doc-hex.
 9002: doc-u.
 9003: doc-.r
 9004: doc-u.r
 9005: doc-d.
 9006: doc-ud.
 9007: doc-d.r
 9008: doc-ud.r
 9009: doc-f.
 9010: doc-fe.
 9011: doc-fs.
 9012: doc-f.rdp
 9013: 
 9014: Examples of printing the number 1234.5678E23 in the different floating-point output
 9015: formats are shown below:
 9016: 
 9017: @example
 9018: f. 123456779999999000000000000.
 9019: fe. 123.456779999999E24
 9020: fs. 1.23456779999999E26
 9021: @end example
 9022: 
 9023: 
 9024: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
 9025: @subsection Formatted numeric output
 9026: @cindex formatted numeric output
 9027: @cindex pictured numeric output
 9028: @cindex numeric output - formatted
 9029: 
 9030: Forth traditionally uses a technique called @dfn{pictured numeric
 9031: output} for formatted printing of integers.  In this technique, digits
 9032: are extracted from the number (using the current output radix defined by
 9033: @code{base}), converted to ASCII codes and appended to a string that is
 9034: built in a scratch-pad area of memory (@pxref{core-idef,
 9035: Implementation-defined options, Implementation-defined
 9036: options}). Arbitrary characters can be appended to the string during the
 9037: extraction process. The completed string is specified by an address
 9038: and length and can be manipulated (@code{TYPE}ed, copied, modified)
 9039: under program control.
 9040: 
 9041: All of the integer output words described in the previous section
 9042: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
 9043: numeric output.
 9044: 
 9045: Three important things to remember about pictured numeric output:
 9046: 
 9047: @itemize @bullet
 9048: @item
 9049: It always operates on double-precision numbers; to display a
 9050: single-precision number, convert it first (for ways of doing this
 9051: @pxref{Double precision}).
 9052: @item
 9053: It always treats the double-precision number as though it were
 9054: unsigned. The examples below show ways of printing signed numbers.
 9055: @item
 9056: The string is built up from right to left; least significant digit first.
 9057: @end itemize
 9058: 
 9059: 
 9060: doc-<#
 9061: doc-<<#
 9062: doc-#
 9063: doc-#s
 9064: doc-hold
 9065: doc-sign
 9066: doc-#>
 9067: doc-#>>
 9068: 
 9069: doc-represent
 9070: doc-f>str-rdp
 9071: doc-f>buf-rdp
 9072: 
 9073: 
 9074: @noindent
 9075: Here are some examples of using pictured numeric output:
 9076: 
 9077: @example
 9078: : my-u. ( u -- )
 9079:   \ Simplest use of pns.. behaves like Standard u. 
 9080:   0              \ convert to unsigned double
 9081:   <<#            \ start conversion
 9082:   #s             \ convert all digits
 9083:   #>             \ complete conversion
 9084:   TYPE SPACE     \ display, with trailing space
 9085:   #>> ;          \ release hold area
 9086: 
 9087: : cents-only ( u -- )
 9088:   0              \ convert to unsigned double
 9089:   <<#            \ start conversion
 9090:   # #            \ convert two least-significant digits
 9091:   #>             \ complete conversion, discard other digits
 9092:   TYPE SPACE     \ display, with trailing space
 9093:   #>> ;          \ release hold area
 9094: 
 9095: : dollars-and-cents ( u -- )
 9096:   0              \ convert to unsigned double
 9097:   <<#            \ start conversion
 9098:   # #            \ convert two least-significant digits
 9099:   [char] . hold  \ insert decimal point
 9100:   #s             \ convert remaining digits
 9101:   [char] $ hold  \ append currency symbol
 9102:   #>             \ complete conversion
 9103:   TYPE SPACE     \ display, with trailing space
 9104:   #>> ;          \ release hold area
 9105: 
 9106: : my-. ( n -- )
 9107:   \ handling negatives.. behaves like Standard .
 9108:   s>d            \ convert to signed double
 9109:   swap over dabs \ leave sign byte followed by unsigned double
 9110:   <<#            \ start conversion
 9111:   #s             \ convert all digits
 9112:   rot sign       \ get at sign byte, append "-" if needed
 9113:   #>             \ complete conversion
 9114:   TYPE SPACE     \ display, with trailing space
 9115:   #>> ;          \ release hold area
 9116: 
 9117: : account. ( n -- )
 9118:   \ accountants don't like minus signs, they use parentheses
 9119:   \ for negative numbers
 9120:   s>d            \ convert to signed double
 9121:   swap over dabs \ leave sign byte followed by unsigned double
 9122:   <<#            \ start conversion
 9123:   2 pick         \ get copy of sign byte
 9124:   0< IF [char] ) hold THEN \ right-most character of output
 9125:   #s             \ convert all digits
 9126:   rot            \ get at sign byte
 9127:   0< IF [char] ( hold THEN
 9128:   #>             \ complete conversion
 9129:   TYPE SPACE     \ display, with trailing space
 9130:   #>> ;          \ release hold area
 9131: 
 9132: @end example
 9133: 
 9134: Here are some examples of using these words:
 9135: 
 9136: @example
 9137: 1 my-u. 1
 9138: hex -1 my-u. decimal FFFFFFFF
 9139: 1 cents-only 01
 9140: 1234 cents-only 34
 9141: 2 dollars-and-cents $0.02
 9142: 1234 dollars-and-cents $12.34
 9143: 123 my-. 123
 9144: -123 my. -123
 9145: 123 account. 123
 9146: -456 account. (456)
 9147: @end example
 9148: 
 9149: 
 9150: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
 9151: @subsection String Formats
 9152: @cindex strings - see character strings
 9153: @cindex character strings - formats
 9154: @cindex I/O - see character strings
 9155: @cindex counted strings
 9156: 
 9157: @c anton: this does not really belong here; maybe the memory section,
 9158: @c  or the principles chapter
 9159: 
 9160: Forth commonly uses two different methods for representing character
 9161: strings:
 9162: 
 9163: @itemize @bullet
 9164: @item
 9165: @cindex address of counted string
 9166: @cindex counted string
 9167: As a @dfn{counted string}, represented by a @i{c-addr}. The char
 9168: addressed by @i{c-addr} contains a character-count, @i{n}, of the
 9169: string and the string occupies the subsequent @i{n} char addresses in
 9170: memory.
 9171: @item
 9172: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
 9173: of the string in characters, and @i{c-addr} is the address of the
 9174: first byte of the string.
 9175: @end itemize
 9176: 
 9177: ANS Forth encourages the use of the second format when representing
 9178: strings.
 9179: 
 9180: 
 9181: doc-count
 9182: 
 9183: 
 9184: For words that move, copy and search for strings see @ref{Memory
 9185: Blocks}. For words that display characters and strings see
 9186: @ref{Displaying characters and strings}.
 9187: 
 9188: @node Displaying characters and strings, String words, String Formats, Other I/O
 9189: @subsection Displaying characters and strings
 9190: @cindex characters - compiling and displaying
 9191: @cindex character strings - compiling and displaying
 9192: 
 9193: This section starts with a glossary of Forth words and ends with a set
 9194: of examples.
 9195: 
 9196: doc-bl
 9197: doc-space
 9198: doc-spaces
 9199: doc-emit
 9200: doc-toupper
 9201: doc-."
 9202: doc-.(
 9203: doc-.\"
 9204: doc-type
 9205: doc-typewhite
 9206: doc-cr
 9207: @cindex cursor control
 9208: doc-s"
 9209: doc-s\"
 9210: doc-c"
 9211: doc-char
 9212: doc-[char]
 9213: 
 9214: 
 9215: @noindent
 9216: As an example, consider the following text, stored in a file @file{test.fs}:
 9217: 
 9218: @example
 9219: .( text-1)
 9220: : my-word
 9221:   ." text-2" cr
 9222:   .( text-3)
 9223: ;
 9224: 
 9225: ." text-4"
 9226: 
 9227: : my-char
 9228:   [char] ALPHABET emit
 9229:   char emit
 9230: ;
 9231: @end example
 9232: 
 9233: When you load this code into Gforth, the following output is generated:
 9234: 
 9235: @example
 9236: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
 9237: @end example
 9238: 
 9239: @itemize @bullet
 9240: @item
 9241: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
 9242: is an immediate word; it behaves in the same way whether it is used inside
 9243: or outside a colon definition.
 9244: @item
 9245: Message @code{text-4} is displayed because of Gforth's added interpretation
 9246: semantics for @code{."}.
 9247: @item
 9248: Message @code{text-2} is @i{not} displayed, because the text interpreter
 9249: performs the compilation semantics for @code{."} within the definition of
 9250: @code{my-word}.
 9251: @end itemize
 9252: 
 9253: Here are some examples of executing @code{my-word} and @code{my-char}:
 9254: 
 9255: @example
 9256: @kbd{my-word @key{RET}} text-2
 9257:  ok
 9258: @kbd{my-char fred @key{RET}} Af ok
 9259: @kbd{my-char jim @key{RET}} Aj ok
 9260: @end example
 9261: 
 9262: @itemize @bullet
 9263: @item
 9264: Message @code{text-2} is displayed because of the run-time behaviour of
 9265: @code{."}.
 9266: @item
 9267: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
 9268: on the stack at run-time. @code{emit} always displays the character
 9269: when @code{my-char} is executed.
 9270: @item
 9271: @code{char} parses a string at run-time and the second @code{emit} displays
 9272: the first character of the string.
 9273: @item
 9274: If you type @code{see my-char} you can see that @code{[char]} discarded
 9275: the text ``LPHABET'' and only compiled the display code for ``A'' into the
 9276: definition of @code{my-char}.
 9277: @end itemize
 9278: 
 9279: @node String words, Terminal output, Displaying characters and strings, Other I/O
 9280: @subsection String words
 9281: @cindex string words
 9282: 
 9283: The following string library stores strings in ordinary variables,
 9284: which then contain a pointer to a counted string stored allocated from
 9285: the heap.  Instead of a count byte, there's a whole count cell,
 9286: sufficient for all normal use.  The string library originates from
 9287: bigFORTH.
 9288: 
 9289: doc-delete
 9290: doc-insert
 9291: doc-$!
 9292: doc-$@
 9293: doc-$@len
 9294: doc-$!len
 9295: doc-$del
 9296: doc-$ins
 9297: doc-$+!
 9298: doc-$off
 9299: doc-$init
 9300: doc-$split
 9301: doc-$iter
 9302: doc-$over
 9303: doc-$[]
 9304: doc-$[]!
 9305: doc-$[]+!
 9306: doc-$[]@
 9307: 
 9308: @node Terminal output, Single-key input, String words, Other I/O
 9309: @subsection Terminal output
 9310: @cindex output to terminal
 9311: @cindex terminal output
 9312: 
 9313: If you are outputting to a terminal, you may want to control the
 9314: positioning of the cursor:
 9315: @cindex cursor positioning
 9316: 
 9317: doc-at-xy
 9318: 
 9319: In order to know where to position the cursor, it is often helpful to
 9320: know the size of the screen:
 9321: @cindex terminal size 
 9322: 
 9323: doc-form
 9324: 
 9325: And sometimes you want to use:
 9326: @cindex clear screen
 9327: 
 9328: doc-page
 9329: 
 9330: Note that on non-terminals you should use @code{12 emit}, not
 9331: @code{page}, to get a form feed.
 9332: 
 9333: 
 9334: @node Single-key input, Line input and conversion, Terminal output, Other I/O
 9335: @subsection Single-key input
 9336: @cindex single-key input
 9337: @cindex input, single-key
 9338: 
 9339: If you want to get a single printable character, you can use
 9340: @code{key}; to check whether a character is available for @code{key},
 9341: you can use @code{key?}.
 9342: 
 9343: doc-key
 9344: doc-key?
 9345: 
 9346: If you want to process a mix of printable and non-printable
 9347: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
 9348: produces a keyboard event that you have to convert into a character
 9349: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
 9350: 
 9351: Typical code for using EKEY looks like this:
 9352: 
 9353: @example
 9354: ekey ekey>char if ( c )
 9355:   ... \ do something with the character
 9356: else ekey>fkey if ( key-id )
 9357:   case
 9358:     k-up                                  of ... endof
 9359:     k-f1                                  of ... endof
 9360:     k-left k-shift-mask or k-ctrl-mask or of ... endof
 9361:     ...
 9362:   endcase
 9363: else ( keyboard-event )
 9364:   drop \ just ignore an unknown keyboard event type
 9365: then then
 9366: @end example
 9367: 
 9368: doc-ekey
 9369: doc-ekey>char
 9370: doc-ekey>fkey
 9371: doc-ekey?
 9372: 
 9373: The key identifiers for cursor keys are:
 9374: 
 9375: doc-k-left
 9376: doc-k-right
 9377: doc-k-up
 9378: doc-k-down
 9379: doc-k-home
 9380: doc-k-end
 9381: doc-k-prior
 9382: doc-k-next
 9383: doc-k-insert
 9384: doc-k-delete
 9385: 
 9386: The key identifiers for function keys (aka keypad keys) are:
 9387: 
 9388: doc-k-f1
 9389: doc-k-f2
 9390: doc-k-f3
 9391: doc-k-f4
 9392: doc-k-f5
 9393: doc-k-f6
 9394: doc-k-f7
 9395: doc-k-f8
 9396: doc-k-f9
 9397: doc-k-f10
 9398: doc-k-f11
 9399: doc-k-f12
 9400: 
 9401: Note that @code{k-f11} and @code{k-f12} are not as widely available.
 9402: 
 9403: You can combine these key identifiers with masks for various shift keys:
 9404: 
 9405: doc-k-shift-mask
 9406: doc-k-ctrl-mask
 9407: doc-k-alt-mask
 9408: 
 9409: Note that, even if a Forth system has @code{ekey>fkey} and the key
 9410: identifier words, the keys are not necessarily available or it may not
 9411: necessarily be able to report all the keys and all the possible
 9412: combinations with shift masks.  Therefore, write your programs in such
 9413: a way that they are still useful even if the keys and key combinations
 9414: cannot be pressed or are not recognized.
 9415: 
 9416: Examples: Older keyboards often do not have an F11 and F12 key.  If
 9417: you run Gforth in an xterm, the xterm catches a number of combinations
 9418: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
 9419: Gforth currently does not recognize and report combinations with
 9420: multiple shift keys (so the @key{shift-ctrl-left} case in the example
 9421: above would never be entered).
 9422: 
 9423: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
 9424: you need the ANSI.SYS driver to get that behaviour); it works by
 9425: recognizing the escape sequences that ANSI terminals send when such a
 9426: key is pressed.  If you have a terminal that sends other escape
 9427: sequences, you will not get useful results on Gforth.  Other Forth
 9428: systems may work in a different way.
 9429: 
 9430: Gforth also provides a few words for outputting names of function
 9431: keys:
 9432: 
 9433: doc-fkey.
 9434: doc-simple-fkey-string
 9435: 
 9436: 
 9437: @node  Line input and conversion, Pipes, Single-key input, Other I/O
 9438: @subsection Line input and conversion
 9439: @cindex line input from terminal
 9440: @cindex input, linewise from terminal
 9441: @cindex convertin strings to numbers
 9442: @cindex I/O - see input
 9443: 
 9444: For ways of storing character strings in memory see @ref{String Formats}.
 9445: 
 9446: @comment TODO examples for >number >float accept key key? pad parse word refill
 9447: @comment then index them
 9448: 
 9449: Words for inputting one line from the keyboard:
 9450: 
 9451: doc-accept
 9452: doc-edit-line
 9453: 
 9454: Conversion words:
 9455: 
 9456: doc-s>number?
 9457: doc-s>unumber?
 9458: doc->number
 9459: doc->float
 9460: doc->float1
 9461: 
 9462: @comment obsolescent words..
 9463: Obsolescent input and conversion words:
 9464: 
 9465: doc-convert
 9466: doc-expect
 9467: doc-span
 9468: 
 9469: 
 9470: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
 9471: @subsection Pipes
 9472: @cindex pipes, creating your own
 9473: 
 9474: In addition to using Gforth in pipes created by other processes
 9475: (@pxref{Gforth in pipes}), you can create your own pipe with
 9476: @code{open-pipe}, and read from or write to it.
 9477: 
 9478: doc-open-pipe
 9479: doc-close-pipe
 9480: 
 9481: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
 9482: you don't catch this exception, Gforth will catch it and exit, usually
 9483: silently (@pxref{Gforth in pipes}).  Since you probably do not want
 9484: this, you should wrap a @code{catch} or @code{try} block around the code
 9485: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
 9486: problem yourself, and then return to regular processing.
 9487: 
 9488: doc-broken-pipe-error
 9489: 
 9490: @node Xchars and Unicode,  , Pipes, Other I/O
 9491: @subsection Xchars and Unicode
 9492: 
 9493: ASCII is only appropriate for the English language. Most western
 9494: languages however fit somewhat into the Forth frame, since a byte is
 9495: sufficient to encode the few special characters in each (though not
 9496: always the same encoding can be used; latin-1 is most widely used,
 9497: though). For other languages, different char-sets have to be used,
 9498: several of them variable-width. Most prominent representant is
 9499: UTF-8. Let's call these extended characters xchars. The primitive
 9500: fixed-size characters stored as bytes are called pchars in this
 9501: section.
 9502: 
 9503: The xchar words add a few data types:
 9504: 
 9505: @itemize
 9506: 
 9507: @item
 9508: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
 9509: and is a subset of unsigned cell. Note: UTF-8 can not store more that
 9510: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
 9511: character set can be used.
 9512: 
 9513: @item
 9514: @var{xc-addr} is the address of an xchar in memory. Alignment
 9515: requirements are the same as @var{c-addr}. The memory representation of an
 9516: xchar differs from the stack representation, and depends on the
 9517: encoding used. An xchar may use a variable number of pchars in memory.
 9518: 
 9519: @item
 9520: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
 9521: @var{xc-addr}, @var{u} pchars long.
 9522: 
 9523: @end itemize
 9524: 
 9525: doc-xc-size
 9526: doc-x-size
 9527: doc-xc@+
 9528: doc-xc!+?
 9529: doc-xchar+
 9530: doc-xchar-
 9531: doc-+x/string
 9532: doc-x\string-
 9533: doc--trailing-garbage
 9534: doc-x-width
 9535: doc-xkey
 9536: doc-xemit
 9537: 
 9538: There's a new environment query
 9539: 
 9540: doc-xchar-encoding
 9541: 
 9542: @node OS command line arguments, Locals, Other I/O, Words
 9543: @section OS command line arguments
 9544: @cindex OS command line arguments
 9545: @cindex command line arguments, OS
 9546: @cindex arguments, OS command line
 9547: 
 9548: The usual way to pass arguments to Gforth programs on the command line
 9549: is via the @option{-e} option, e.g.
 9550: 
 9551: @example
 9552: gforth -e "123 456" foo.fs -e bye
 9553: @end example
 9554: 
 9555: However, you may want to interpret the command-line arguments directly.
 9556: In that case, you can access the (image-specific) command-line arguments
 9557: through @code{next-arg}:
 9558: 
 9559: doc-next-arg
 9560: 
 9561: Here's an example program @file{echo.fs} for @code{next-arg}:
 9562: 
 9563: @example
 9564: : echo ( -- )
 9565:     begin
 9566: 	next-arg 2dup 0 0 d<> while
 9567: 	    type space
 9568:     repeat
 9569:     2drop ;
 9570: 
 9571: echo cr bye
 9572: @end example
 9573: 
 9574: This can be invoked with
 9575: 
 9576: @example
 9577: gforth echo.fs hello world
 9578: @end example
 9579: 
 9580: and it will print
 9581: 
 9582: @example
 9583: hello world
 9584: @end example
 9585: 
 9586: The next lower level of dealing with the OS command line are the
 9587: following words:
 9588: 
 9589: doc-arg
 9590: doc-shift-args
 9591: 
 9592: Finally, at the lowest level Gforth provides the following words:
 9593: 
 9594: doc-argc
 9595: doc-argv
 9596: 
 9597: @c -------------------------------------------------------------
 9598: @node Locals, Structures, OS command line arguments, Words
 9599: @section Locals
 9600: @cindex locals
 9601: 
 9602: Local variables can make Forth programming more enjoyable and Forth
 9603: programs easier to read. Unfortunately, the locals of ANS Forth are
 9604: laden with restrictions. Therefore, we provide not only the ANS Forth
 9605: locals wordset, but also our own, more powerful locals wordset (we
 9606: implemented the ANS Forth locals wordset through our locals wordset).
 9607: 
 9608: The ideas in this section have also been published in M. Anton Ertl,
 9609: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
 9610: Automatic Scoping of Local Variables}}, EuroForth '94.
 9611: 
 9612: @menu
 9613: * Gforth locals::               
 9614: * ANS Forth locals::            
 9615: @end menu
 9616: 
 9617: @node Gforth locals, ANS Forth locals, Locals, Locals
 9618: @subsection Gforth locals
 9619: @cindex Gforth locals
 9620: @cindex locals, Gforth style
 9621: 
 9622: Locals can be defined with
 9623: 
 9624: @example
 9625: @{ local1 local2 ... -- comment @}
 9626: @end example
 9627: or
 9628: @example
 9629: @{ local1 local2 ... @}
 9630: @end example
 9631: 
 9632: E.g.,
 9633: @example
 9634: : max @{ n1 n2 -- n3 @}
 9635:  n1 n2 > if
 9636:    n1
 9637:  else
 9638:    n2
 9639:  endif ;
 9640: @end example
 9641: 
 9642: The similarity of locals definitions with stack comments is intended. A
 9643: locals definition often replaces the stack comment of a word. The order
 9644: of the locals corresponds to the order in a stack comment and everything
 9645: after the @code{--} is really a comment.
 9646: 
 9647: This similarity has one disadvantage: It is too easy to confuse locals
 9648: declarations with stack comments, causing bugs and making them hard to
 9649: find. However, this problem can be avoided by appropriate coding
 9650: conventions: Do not use both notations in the same program. If you do,
 9651: they should be distinguished using additional means, e.g. by position.
 9652: 
 9653: @cindex types of locals
 9654: @cindex locals types
 9655: The name of the local may be preceded by a type specifier, e.g.,
 9656: @code{F:} for a floating point value:
 9657: 
 9658: @example
 9659: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
 9660: \ complex multiplication
 9661:  Ar Br f* Ai Bi f* f-
 9662:  Ar Bi f* Ai Br f* f+ ;
 9663: @end example
 9664: 
 9665: @cindex flavours of locals
 9666: @cindex locals flavours
 9667: @cindex value-flavoured locals
 9668: @cindex variable-flavoured locals
 9669: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
 9670: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
 9671: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
 9672: with @code{W:}, @code{D:} etc.) produces its value and can be changed
 9673: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
 9674: produces its address (which becomes invalid when the variable's scope is
 9675: left). E.g., the standard word @code{emit} can be defined in terms of
 9676: @code{type} like this:
 9677: 
 9678: @example
 9679: : emit @{ C^ char* -- @}
 9680:     char* 1 type ;
 9681: @end example
 9682: 
 9683: @cindex default type of locals
 9684: @cindex locals, default type
 9685: A local without type specifier is a @code{W:} local. Both flavours of
 9686: locals are initialized with values from the data or FP stack.
 9687: 
 9688: Currently there is no way to define locals with user-defined data
 9689: structures, but we are working on it.
 9690: 
 9691: Gforth allows defining locals everywhere in a colon definition. This
 9692: poses the following questions:
 9693: 
 9694: @menu
 9695: * Where are locals visible by name?::  
 9696: * How long do locals live?::    
 9697: * Locals programming style::    
 9698: * Locals implementation::       
 9699: @end menu
 9700: 
 9701: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
 9702: @subsubsection Where are locals visible by name?
 9703: @cindex locals visibility
 9704: @cindex visibility of locals
 9705: @cindex scope of locals
 9706: 
 9707: Basically, the answer is that locals are visible where you would expect
 9708: it in block-structured languages, and sometimes a little longer. If you
 9709: want to restrict the scope of a local, enclose its definition in
 9710: @code{SCOPE}...@code{ENDSCOPE}.
 9711: 
 9712: 
 9713: doc-scope
 9714: doc-endscope
 9715: 
 9716: 
 9717: These words behave like control structure words, so you can use them
 9718: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
 9719: arbitrary ways.
 9720: 
 9721: If you want a more exact answer to the visibility question, here's the
 9722: basic principle: A local is visible in all places that can only be
 9723: reached through the definition of the local@footnote{In compiler
 9724: construction terminology, all places dominated by the definition of the
 9725: local.}. In other words, it is not visible in places that can be reached
 9726: without going through the definition of the local. E.g., locals defined
 9727: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
 9728: defined in @code{BEGIN}...@code{UNTIL} are visible after the
 9729: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
 9730: 
 9731: The reasoning behind this solution is: We want to have the locals
 9732: visible as long as it is meaningful. The user can always make the
 9733: visibility shorter by using explicit scoping. In a place that can
 9734: only be reached through the definition of a local, the meaning of a
 9735: local name is clear. In other places it is not: How is the local
 9736: initialized at the control flow path that does not contain the
 9737: definition? Which local is meant, if the same name is defined twice in
 9738: two independent control flow paths?
 9739: 
 9740: This should be enough detail for nearly all users, so you can skip the
 9741: rest of this section. If you really must know all the gory details and
 9742: options, read on.
 9743: 
 9744: In order to implement this rule, the compiler has to know which places
 9745: are unreachable. It knows this automatically after @code{AHEAD},
 9746: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
 9747: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
 9748: compiler that the control flow never reaches that place. If
 9749: @code{UNREACHABLE} is not used where it could, the only consequence is
 9750: that the visibility of some locals is more limited than the rule above
 9751: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
 9752: lie to the compiler), buggy code will be produced.
 9753: 
 9754: 
 9755: doc-unreachable
 9756: 
 9757: 
 9758: Another problem with this rule is that at @code{BEGIN}, the compiler
 9759: does not know which locals will be visible on the incoming
 9760: back-edge. All problems discussed in the following are due to this
 9761: ignorance of the compiler (we discuss the problems using @code{BEGIN}
 9762: loops as examples; the discussion also applies to @code{?DO} and other
 9763: loops). Perhaps the most insidious example is:
 9764: @example
 9765: AHEAD
 9766: BEGIN
 9767:   x
 9768: [ 1 CS-ROLL ] THEN
 9769:   @{ x @}
 9770:   ...
 9771: UNTIL
 9772: @end example
 9773: 
 9774: This should be legal according to the visibility rule. The use of
 9775: @code{x} can only be reached through the definition; but that appears
 9776: textually below the use.
 9777: 
 9778: From this example it is clear that the visibility rules cannot be fully
 9779: implemented without major headaches. Our implementation treats common
 9780: cases as advertised and the exceptions are treated in a safe way: The
 9781: compiler makes a reasonable guess about the locals visible after a
 9782: @code{BEGIN}; if it is too pessimistic, the
 9783: user will get a spurious error about the local not being defined; if the
 9784: compiler is too optimistic, it will notice this later and issue a
 9785: warning. In the case above the compiler would complain about @code{x}
 9786: being undefined at its use. You can see from the obscure examples in
 9787: this section that it takes quite unusual control structures to get the
 9788: compiler into trouble, and even then it will often do fine.
 9789: 
 9790: If the @code{BEGIN} is reachable from above, the most optimistic guess
 9791: is that all locals visible before the @code{BEGIN} will also be
 9792: visible after the @code{BEGIN}. This guess is valid for all loops that
 9793: are entered only through the @code{BEGIN}, in particular, for normal
 9794: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
 9795: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
 9796: compiler. When the branch to the @code{BEGIN} is finally generated by
 9797: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
 9798: warns the user if it was too optimistic:
 9799: @example
 9800: IF
 9801:   @{ x @}
 9802: BEGIN
 9803:   \ x ? 
 9804: [ 1 cs-roll ] THEN
 9805:   ...
 9806: UNTIL
 9807: @end example
 9808: 
 9809: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
 9810: optimistically assumes that it lives until the @code{THEN}. It notices
 9811: this difference when it compiles the @code{UNTIL} and issues a
 9812: warning. The user can avoid the warning, and make sure that @code{x}
 9813: is not used in the wrong area by using explicit scoping:
 9814: @example
 9815: IF
 9816:   SCOPE
 9817:   @{ x @}
 9818:   ENDSCOPE
 9819: BEGIN
 9820: [ 1 cs-roll ] THEN
 9821:   ...
 9822: UNTIL
 9823: @end example
 9824: 
 9825: Since the guess is optimistic, there will be no spurious error messages
 9826: about undefined locals.
 9827: 
 9828: If the @code{BEGIN} is not reachable from above (e.g., after
 9829: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
 9830: optimistic guess, as the locals visible after the @code{BEGIN} may be
 9831: defined later. Therefore, the compiler assumes that no locals are
 9832: visible after the @code{BEGIN}. However, the user can use
 9833: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
 9834: visible at the BEGIN as at the point where the top control-flow stack
 9835: item was created.
 9836: 
 9837: 
 9838: doc-assume-live
 9839: 
 9840: 
 9841: @noindent
 9842: E.g.,
 9843: @example
 9844: @{ x @}
 9845: AHEAD
 9846: ASSUME-LIVE
 9847: BEGIN
 9848:   x
 9849: [ 1 CS-ROLL ] THEN
 9850:   ...
 9851: UNTIL
 9852: @end example
 9853: 
 9854: Other cases where the locals are defined before the @code{BEGIN} can be
 9855: handled by inserting an appropriate @code{CS-ROLL} before the
 9856: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
 9857: behind the @code{ASSUME-LIVE}).
 9858: 
 9859: Cases where locals are defined after the @code{BEGIN} (but should be
 9860: visible immediately after the @code{BEGIN}) can only be handled by
 9861: rearranging the loop. E.g., the ``most insidious'' example above can be
 9862: arranged into:
 9863: @example
 9864: BEGIN
 9865:   @{ x @}
 9866:   ... 0=
 9867: WHILE
 9868:   x
 9869: REPEAT
 9870: @end example
 9871: 
 9872: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
 9873: @subsubsection How long do locals live?
 9874: @cindex locals lifetime
 9875: @cindex lifetime of locals
 9876: 
 9877: The right answer for the lifetime question would be: A local lives at
 9878: least as long as it can be accessed. For a value-flavoured local this
 9879: means: until the end of its visibility. However, a variable-flavoured
 9880: local could be accessed through its address far beyond its visibility
 9881: scope. Ultimately, this would mean that such locals would have to be
 9882: garbage collected. Since this entails un-Forth-like implementation
 9883: complexities, I adopted the same cowardly solution as some other
 9884: languages (e.g., C): The local lives only as long as it is visible;
 9885: afterwards its address is invalid (and programs that access it
 9886: afterwards are erroneous).
 9887: 
 9888: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
 9889: @subsubsection Locals programming style
 9890: @cindex locals programming style
 9891: @cindex programming style, locals
 9892: 
 9893: The freedom to define locals anywhere has the potential to change
 9894: programming styles dramatically. In particular, the need to use the
 9895: return stack for intermediate storage vanishes. Moreover, all stack
 9896: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
 9897: determined arguments) can be eliminated: If the stack items are in the
 9898: wrong order, just write a locals definition for all of them; then
 9899: write the items in the order you want.
 9900: 
 9901: This seems a little far-fetched and eliminating stack manipulations is
 9902: unlikely to become a conscious programming objective. Still, the number
 9903: of stack manipulations will be reduced dramatically if local variables
 9904: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
 9905: a traditional implementation of @code{max}).
 9906: 
 9907: This shows one potential benefit of locals: making Forth programs more
 9908: readable. Of course, this benefit will only be realized if the
 9909: programmers continue to honour the principle of factoring instead of
 9910: using the added latitude to make the words longer.
 9911: 
 9912: @cindex single-assignment style for locals
 9913: Using @code{TO} can and should be avoided.  Without @code{TO},
 9914: every value-flavoured local has only a single assignment and many
 9915: advantages of functional languages apply to Forth. I.e., programs are
 9916: easier to analyse, to optimize and to read: It is clear from the
 9917: definition what the local stands for, it does not turn into something
 9918: different later.
 9919: 
 9920: E.g., a definition using @code{TO} might look like this:
 9921: @example
 9922: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9923:  u1 u2 min 0
 9924:  ?do
 9925:    addr1 c@@ addr2 c@@ -
 9926:    ?dup-if
 9927:      unloop exit
 9928:    then
 9929:    addr1 char+ TO addr1
 9930:    addr2 char+ TO addr2
 9931:  loop
 9932:  u1 u2 - ;
 9933: @end example
 9934: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
 9935: every loop iteration. @code{strcmp} is a typical example of the
 9936: readability problems of using @code{TO}. When you start reading
 9937: @code{strcmp}, you think that @code{addr1} refers to the start of the
 9938: string. Only near the end of the loop you realize that it is something
 9939: else.
 9940: 
 9941: This can be avoided by defining two locals at the start of the loop that
 9942: are initialized with the right value for the current iteration.
 9943: @example
 9944: : strcmp @{ addr1 u1 addr2 u2 -- n @}
 9945:  addr1 addr2
 9946:  u1 u2 min 0 
 9947:  ?do @{ s1 s2 @}
 9948:    s1 c@@ s2 c@@ -
 9949:    ?dup-if
 9950:      unloop exit
 9951:    then
 9952:    s1 char+ s2 char+
 9953:  loop
 9954:  2drop
 9955:  u1 u2 - ;
 9956: @end example
 9957: Here it is clear from the start that @code{s1} has a different value
 9958: in every loop iteration.
 9959: 
 9960: @node Locals implementation,  , Locals programming style, Gforth locals
 9961: @subsubsection Locals implementation
 9962: @cindex locals implementation
 9963: @cindex implementation of locals
 9964: 
 9965: @cindex locals stack
 9966: Gforth uses an extra locals stack. The most compelling reason for
 9967: this is that the return stack is not float-aligned; using an extra stack
 9968: also eliminates the problems and restrictions of using the return stack
 9969: as locals stack. Like the other stacks, the locals stack grows toward
 9970: lower addresses. A few primitives allow an efficient implementation:
 9971: 
 9972: 
 9973: doc-@local#
 9974: doc-f@local#
 9975: doc-laddr#
 9976: doc-lp+!#
 9977: doc-lp!
 9978: doc->l
 9979: doc-f>l
 9980: 
 9981: 
 9982: In addition to these primitives, some specializations of these
 9983: primitives for commonly occurring inline arguments are provided for
 9984: efficiency reasons, e.g., @code{@@local0} as specialization of
 9985: @code{@@local#} for the inline argument 0. The following compiling words
 9986: compile the right specialized version, or the general version, as
 9987: appropriate:
 9988: 
 9989: 
 9990: @c doc-compile-@local
 9991: @c doc-compile-f@local
 9992: doc-compile-lp+!
 9993: 
 9994: 
 9995: Combinations of conditional branches and @code{lp+!#} like
 9996: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
 9997: is taken) are provided for efficiency and correctness in loops.
 9998: 
 9999: A special area in the dictionary space is reserved for keeping the
10000: local variable names. @code{@{} switches the dictionary pointer to this
10001: area and @code{@}} switches it back and generates the locals
10002: initializing code. @code{W:} etc.@ are normal defining words. This
10003: special area is cleared at the start of every colon definition.
10004: 
10005: @cindex word list for defining locals
10006: A special feature of Gforth's dictionary is used to implement the
10007: definition of locals without type specifiers: every word list (aka
10008: vocabulary) has its own methods for searching
10009: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
10010: with a special search method: When it is searched for a word, it
10011: actually creates that word using @code{W:}. @code{@{} changes the search
10012: order to first search the word list containing @code{@}}, @code{W:} etc.,
10013: and then the word list for defining locals without type specifiers.
10014: 
10015: The lifetime rules support a stack discipline within a colon
10016: definition: The lifetime of a local is either nested with other locals
10017: lifetimes or it does not overlap them.
10018: 
10019: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
10020: pointer manipulation is generated. Between control structure words
10021: locals definitions can push locals onto the locals stack. @code{AGAIN}
10022: is the simplest of the other three control flow words. It has to
10023: restore the locals stack depth of the corresponding @code{BEGIN}
10024: before branching. The code looks like this:
10025: @format
10026: @code{lp+!#} current-locals-size @minus{} dest-locals-size
10027: @code{branch} <begin>
10028: @end format
10029: 
10030: @code{UNTIL} is a little more complicated: If it branches back, it
10031: must adjust the stack just like @code{AGAIN}. But if it falls through,
10032: the locals stack must not be changed. The compiler generates the
10033: following code:
10034: @format
10035: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
10036: @end format
10037: The locals stack pointer is only adjusted if the branch is taken.
10038: 
10039: @code{THEN} can produce somewhat inefficient code:
10040: @format
10041: @code{lp+!#} current-locals-size @minus{} orig-locals-size
10042: <orig target>:
10043: @code{lp+!#} orig-locals-size @minus{} new-locals-size
10044: @end format
10045: The second @code{lp+!#} adjusts the locals stack pointer from the
10046: level at the @i{orig} point to the level after the @code{THEN}. The
10047: first @code{lp+!#} adjusts the locals stack pointer from the current
10048: level to the level at the orig point, so the complete effect is an
10049: adjustment from the current level to the right level after the
10050: @code{THEN}.
10051: 
10052: @cindex locals information on the control-flow stack
10053: @cindex control-flow stack items, locals information
10054: In a conventional Forth implementation a dest control-flow stack entry
10055: is just the target address and an orig entry is just the address to be
10056: patched. Our locals implementation adds a word list to every orig or dest
10057: item. It is the list of locals visible (or assumed visible) at the point
10058: described by the entry. Our implementation also adds a tag to identify
10059: the kind of entry, in particular to differentiate between live and dead
10060: (reachable and unreachable) orig entries.
10061: 
10062: A few unusual operations have to be performed on locals word lists:
10063: 
10064: 
10065: doc-common-list
10066: doc-sub-list?
10067: doc-list-size
10068: 
10069: 
10070: Several features of our locals word list implementation make these
10071: operations easy to implement: The locals word lists are organised as
10072: linked lists; the tails of these lists are shared, if the lists
10073: contain some of the same locals; and the address of a name is greater
10074: than the address of the names behind it in the list.
10075: 
10076: Another important implementation detail is the variable
10077: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
10078: determine if they can be reached directly or only through the branch
10079: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
10080: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
10081: definition, by @code{BEGIN} and usually by @code{THEN}.
10082: 
10083: Counted loops are similar to other loops in most respects, but
10084: @code{LEAVE} requires special attention: It performs basically the same
10085: service as @code{AHEAD}, but it does not create a control-flow stack
10086: entry. Therefore the information has to be stored elsewhere;
10087: traditionally, the information was stored in the target fields of the
10088: branches created by the @code{LEAVE}s, by organizing these fields into a
10089: linked list. Unfortunately, this clever trick does not provide enough
10090: space for storing our extended control flow information. Therefore, we
10091: introduce another stack, the leave stack. It contains the control-flow
10092: stack entries for all unresolved @code{LEAVE}s.
10093: 
10094: Local names are kept until the end of the colon definition, even if
10095: they are no longer visible in any control-flow path. In a few cases
10096: this may lead to increased space needs for the locals name area, but
10097: usually less than reclaiming this space would cost in code size.
10098: 
10099: 
10100: @node ANS Forth locals,  , Gforth locals, Locals
10101: @subsection ANS Forth locals
10102: @cindex locals, ANS Forth style
10103: 
10104: The ANS Forth locals wordset does not define a syntax for locals, but
10105: words that make it possible to define various syntaxes. One of the
10106: possible syntaxes is a subset of the syntax we used in the Gforth locals
10107: wordset, i.e.:
10108: 
10109: @example
10110: @{ local1 local2 ... -- comment @}
10111: @end example
10112: @noindent
10113: or
10114: @example
10115: @{ local1 local2 ... @}
10116: @end example
10117: 
10118: The order of the locals corresponds to the order in a stack comment. The
10119: restrictions are:
10120: 
10121: @itemize @bullet
10122: @item
10123: Locals can only be cell-sized values (no type specifiers are allowed).
10124: @item
10125: Locals can be defined only outside control structures.
10126: @item
10127: Locals can interfere with explicit usage of the return stack. For the
10128: exact (and long) rules, see the standard. If you don't use return stack
10129: accessing words in a definition using locals, you will be all right. The
10130: purpose of this rule is to make locals implementation on the return
10131: stack easier.
10132: @item
10133: The whole definition must be in one line.
10134: @end itemize
10135: 
10136: Locals defined in ANS Forth behave like @code{VALUE}s
10137: (@pxref{Values}). I.e., they are initialized from the stack. Using their
10138: name produces their value. Their value can be changed using @code{TO}.
10139: 
10140: Since the syntax above is supported by Gforth directly, you need not do
10141: anything to use it. If you want to port a program using this syntax to
10142: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
10143: syntax on the other system.
10144: 
10145: Note that a syntax shown in the standard, section A.13 looks
10146: similar, but is quite different in having the order of locals
10147: reversed. Beware!
10148: 
10149: The ANS Forth locals wordset itself consists of one word:
10150: 
10151: doc-(local)
10152: 
10153: The ANS Forth locals extension wordset defines a syntax using
10154: @code{locals|}, but it is so awful that we strongly recommend not to use
10155: it. We have implemented this syntax to make porting to Gforth easy, but
10156: do not document it here. The problem with this syntax is that the locals
10157: are defined in an order reversed with respect to the standard stack
10158: comment notation, making programs harder to read, and easier to misread
10159: and miswrite. The only merit of this syntax is that it is easy to
10160: implement using the ANS Forth locals wordset.
10161: 
10162: 
10163: @c ----------------------------------------------------------
10164: @node Structures, Object-oriented Forth, Locals, Words
10165: @section  Structures
10166: @cindex structures
10167: @cindex records
10168: 
10169: This section presents the structure package that comes with Gforth. A
10170: version of the package implemented in ANS Forth is available in
10171: @file{compat/struct.fs}. This package was inspired by a posting on
10172: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
10173: possibly John Hayes). A version of this section has been published in
10174: M. Anton Ertl,
10175: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
10176: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10177: 13--16. Marcel Hendrix provided helpful comments.
10178: 
10179: @menu
10180: * Why explicit structure support?::  
10181: * Structure Usage::             
10182: * Structure Naming Convention::  
10183: * Structure Implementation::    
10184: * Structure Glossary::          
10185: * Forth200x Structures::        
10186: @end menu
10187: 
10188: @node Why explicit structure support?, Structure Usage, Structures, Structures
10189: @subsection Why explicit structure support?
10190: 
10191: @cindex address arithmetic for structures
10192: @cindex structures using address arithmetic
10193: If we want to use a structure containing several fields, we could simply
10194: reserve memory for it, and access the fields using address arithmetic
10195: (@pxref{Address arithmetic}). As an example, consider a structure with
10196: the following fields
10197: 
10198: @table @code
10199: @item a
10200: is a float
10201: @item b
10202: is a cell
10203: @item c
10204: is a float
10205: @end table
10206: 
10207: Given the (float-aligned) base address of the structure we get the
10208: address of the field
10209: 
10210: @table @code
10211: @item a
10212: without doing anything further.
10213: @item b
10214: with @code{float+}
10215: @item c
10216: with @code{float+ cell+ faligned}
10217: @end table
10218: 
10219: It is easy to see that this can become quite tiring. 
10220: 
10221: Moreover, it is not very readable, because seeing a
10222: @code{cell+} tells us neither which kind of structure is
10223: accessed nor what field is accessed; we have to somehow infer the kind
10224: of structure, and then look up in the documentation, which field of
10225: that structure corresponds to that offset.
10226: 
10227: Finally, this kind of address arithmetic also causes maintenance
10228: troubles: If you add or delete a field somewhere in the middle of the
10229: structure, you have to find and change all computations for the fields
10230: afterwards.
10231: 
10232: So, instead of using @code{cell+} and friends directly, how
10233: about storing the offsets in constants:
10234: 
10235: @example
10236: 0 constant a-offset
10237: 0 float+ constant b-offset
10238: 0 float+ cell+ faligned c-offset
10239: @end example
10240: 
10241: Now we can get the address of field @code{x} with @code{x-offset
10242: +}. This is much better in all respects. Of course, you still
10243: have to change all later offset definitions if you add a field. You can
10244: fix this by declaring the offsets in the following way:
10245: 
10246: @example
10247: 0 constant a-offset
10248: a-offset float+ constant b-offset
10249: b-offset cell+ faligned constant c-offset
10250: @end example
10251: 
10252: Since we always use the offsets with @code{+}, we could use a defining
10253: word @code{cfield} that includes the @code{+} in the action of the
10254: defined word:
10255: 
10256: @example
10257: : cfield ( n "name" -- )
10258:     create ,
10259: does> ( name execution: addr1 -- addr2 )
10260:     @@ + ;
10261: 
10262: 0 cfield a
10263: 0 a float+ cfield b
10264: 0 b cell+ faligned cfield c
10265: @end example
10266: 
10267: Instead of @code{x-offset +}, we now simply write @code{x}.
10268: 
10269: The structure field words now can be used quite nicely. However,
10270: their definition is still a bit cumbersome: We have to repeat the
10271: name, the information about size and alignment is distributed before
10272: and after the field definitions etc.  The structure package presented
10273: here addresses these problems.
10274: 
10275: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10276: @subsection Structure Usage
10277: @cindex structure usage
10278: 
10279: @cindex @code{field} usage
10280: @cindex @code{struct} usage
10281: @cindex @code{end-struct} usage
10282: You can define a structure for a (data-less) linked list with:
10283: @example
10284: struct
10285:     cell% field list-next
10286: end-struct list%
10287: @end example
10288: 
10289: With the address of the list node on the stack, you can compute the
10290: address of the field that contains the address of the next node with
10291: @code{list-next}. E.g., you can determine the length of a list
10292: with:
10293: 
10294: @example
10295: : list-length ( list -- n )
10296: \ "list" is a pointer to the first element of a linked list
10297: \ "n" is the length of the list
10298:     0 BEGIN ( list1 n1 )
10299:         over
10300:     WHILE ( list1 n1 )
10301:         1+ swap list-next @@ swap
10302:     REPEAT
10303:     nip ;
10304: @end example
10305: 
10306: You can reserve memory for a list node in the dictionary with
10307: @code{list% %allot}, which leaves the address of the list node on the
10308: stack. For the equivalent allocation on the heap you can use @code{list%
10309: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10310: use @code{list% %allocate}). You can get the the size of a list
10311: node with @code{list% %size} and its alignment with @code{list%
10312: %alignment}.
10313: 
10314: Note that in ANS Forth the body of a @code{create}d word is
10315: @code{aligned} but not necessarily @code{faligned};
10316: therefore, if you do a:
10317: 
10318: @example
10319: create @emph{name} foo% %allot drop
10320: @end example
10321: 
10322: @noindent
10323: then the memory alloted for @code{foo%} is guaranteed to start at the
10324: body of @code{@emph{name}} only if @code{foo%} contains only character,
10325: cell and double fields.  Therefore, if your structure contains floats,
10326: better use
10327: 
10328: @example
10329: foo% %allot constant @emph{name}
10330: @end example
10331: 
10332: @cindex structures containing structures
10333: You can include a structure @code{foo%} as a field of
10334: another structure, like this:
10335: @example
10336: struct
10337: ...
10338:     foo% field ...
10339: ...
10340: end-struct ...
10341: @end example
10342: 
10343: @cindex structure extension
10344: @cindex extended records
10345: Instead of starting with an empty structure, you can extend an
10346: existing structure. E.g., a plain linked list without data, as defined
10347: above, is hardly useful; You can extend it to a linked list of integers,
10348: like this:@footnote{This feature is also known as @emph{extended
10349: records}. It is the main innovation in the Oberon language; in other
10350: words, adding this feature to Modula-2 led Wirth to create a new
10351: language, write a new compiler etc.  Adding this feature to Forth just
10352: required a few lines of code.}
10353: 
10354: @example
10355: list%
10356:     cell% field intlist-int
10357: end-struct intlist%
10358: @end example
10359: 
10360: @code{intlist%} is a structure with two fields:
10361: @code{list-next} and @code{intlist-int}.
10362: 
10363: @cindex structures containing arrays
10364: You can specify an array type containing @emph{n} elements of
10365: type @code{foo%} like this:
10366: 
10367: @example
10368: foo% @emph{n} *
10369: @end example
10370: 
10371: You can use this array type in any place where you can use a normal
10372: type, e.g., when defining a @code{field}, or with
10373: @code{%allot}.
10374: 
10375: @cindex first field optimization
10376: The first field is at the base address of a structure and the word for
10377: this field (e.g., @code{list-next}) actually does not change the address
10378: on the stack. You may be tempted to leave it away in the interest of
10379: run-time and space efficiency. This is not necessary, because the
10380: structure package optimizes this case: If you compile a first-field
10381: words, no code is generated. So, in the interest of readability and
10382: maintainability you should include the word for the field when accessing
10383: the field.
10384: 
10385: 
10386: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10387: @subsection Structure Naming Convention
10388: @cindex structure naming convention
10389: 
10390: The field names that come to (my) mind are often quite generic, and,
10391: if used, would cause frequent name clashes. E.g., many structures
10392: probably contain a @code{counter} field. The structure names
10393: that come to (my) mind are often also the logical choice for the names
10394: of words that create such a structure.
10395: 
10396: Therefore, I have adopted the following naming conventions: 
10397: 
10398: @itemize @bullet
10399: @cindex field naming convention
10400: @item
10401: The names of fields are of the form
10402: @code{@emph{struct}-@emph{field}}, where
10403: @code{@emph{struct}} is the basic name of the structure, and
10404: @code{@emph{field}} is the basic name of the field. You can
10405: think of field words as converting the (address of the)
10406: structure into the (address of the) field.
10407: 
10408: @cindex structure naming convention
10409: @item
10410: The names of structures are of the form
10411: @code{@emph{struct}%}, where
10412: @code{@emph{struct}} is the basic name of the structure.
10413: @end itemize
10414: 
10415: This naming convention does not work that well for fields of extended
10416: structures; e.g., the integer list structure has a field
10417: @code{intlist-int}, but has @code{list-next}, not
10418: @code{intlist-next}.
10419: 
10420: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10421: @subsection Structure Implementation
10422: @cindex structure implementation
10423: @cindex implementation of structures
10424: 
10425: The central idea in the implementation is to pass the data about the
10426: structure being built on the stack, not in some global
10427: variable. Everything else falls into place naturally once this design
10428: decision is made.
10429: 
10430: The type description on the stack is of the form @emph{align
10431: size}. Keeping the size on the top-of-stack makes dealing with arrays
10432: very simple.
10433: 
10434: @code{field} is a defining word that uses @code{Create}
10435: and @code{DOES>}. The body of the field contains the offset
10436: of the field, and the normal @code{DOES>} action is simply:
10437: 
10438: @example
10439: @@ +
10440: @end example
10441: 
10442: @noindent
10443: i.e., add the offset to the address, giving the stack effect
10444: @i{addr1 -- addr2} for a field.
10445: 
10446: @cindex first field optimization, implementation
10447: This simple structure is slightly complicated by the optimization
10448: for fields with offset 0, which requires a different
10449: @code{DOES>}-part (because we cannot rely on there being
10450: something on the stack if such a field is invoked during
10451: compilation). Therefore, we put the different @code{DOES>}-parts
10452: in separate words, and decide which one to invoke based on the
10453: offset. For a zero offset, the field is basically a noop; it is
10454: immediate, and therefore no code is generated when it is compiled.
10455: 
10456: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
10457: @subsection Structure Glossary
10458: @cindex structure glossary
10459: 
10460: 
10461: doc-%align
10462: doc-%alignment
10463: doc-%alloc
10464: doc-%allocate
10465: doc-%allot
10466: doc-cell%
10467: doc-char%
10468: doc-dfloat%
10469: doc-double%
10470: doc-end-struct
10471: doc-field
10472: doc-float%
10473: doc-naligned
10474: doc-sfloat%
10475: doc-%size
10476: doc-struct
10477: 
10478: 
10479: @node Forth200x Structures,  , Structure Glossary, Structures
10480: @subsection Forth200x Structures
10481: @cindex Structures in Forth200x
10482: 
10483: The Forth 200x standard defines a slightly less convenient form of
10484: structures.  In general (when using @code{field+}, you have to perform
10485: the alignment yourself, but there are a number of convenience words
10486: (e.g., @code{field:} that perform the alignment for you.
10487: 
10488: A typical usage example is:
10489: 
10490: @example
10491: 0
10492:   field:                   s-a
10493:   faligned 2 floats +field s-b
10494: constant s-struct
10495: @end example
10496: 
10497: An alternative way of writing this structure is:
10498: 
10499: @example
10500: begin-structure s-struct
10501:   field:                   s-a
10502:   faligned 2 floats +field s-b
10503: end-structure
10504: @end example
10505: 
10506: doc-begin-structure
10507: doc-end-structure
10508: doc-+field
10509: doc-cfield:
10510: doc-field:
10511: doc-2field:
10512: doc-ffield:
10513: doc-sffield:
10514: doc-dffield:
10515: 
10516: @c -------------------------------------------------------------
10517: @node Object-oriented Forth, Programming Tools, Structures, Words
10518: @section Object-oriented Forth
10519: 
10520: Gforth comes with three packages for object-oriented programming:
10521: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10522: is preloaded, so you have to @code{include} them before use. The most
10523: important differences between these packages (and others) are discussed
10524: in @ref{Comparison with other object models}. All packages are written
10525: in ANS Forth and can be used with any other ANS Forth.
10526: 
10527: @menu
10528: * Why object-oriented programming?::  
10529: * Object-Oriented Terminology::  
10530: * Objects::                     
10531: * OOF::                         
10532: * Mini-OOF::                    
10533: * Comparison with other object models::  
10534: @end menu
10535: 
10536: @c ----------------------------------------------------------------
10537: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10538: @subsection Why object-oriented programming?
10539: @cindex object-oriented programming motivation
10540: @cindex motivation for object-oriented programming
10541: 
10542: Often we have to deal with several data structures (@emph{objects}),
10543: that have to be treated similarly in some respects, but differently in
10544: others. Graphical objects are the textbook example: circles, triangles,
10545: dinosaurs, icons, and others, and we may want to add more during program
10546: development. We want to apply some operations to any graphical object,
10547: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10548: has to do something different for every kind of object.
10549: @comment TODO add some other operations eg perimeter, area
10550: @comment and tie in to concrete examples later..
10551: 
10552: We could implement @code{draw} as a big @code{CASE}
10553: control structure that executes the appropriate code depending on the
10554: kind of object to be drawn. This would be not be very elegant, and,
10555: moreover, we would have to change @code{draw} every time we add
10556: a new kind of graphical object (say, a spaceship).
10557: 
10558: What we would rather do is: When defining spaceships, we would tell
10559: the system: ``Here's how you @code{draw} a spaceship; you figure
10560: out the rest''.
10561: 
10562: This is the problem that all systems solve that (rightfully) call
10563: themselves object-oriented; the object-oriented packages presented here
10564: solve this problem (and not much else).
10565: @comment TODO ?list properties of oo systems.. oo vs o-based?
10566: 
10567: @c ------------------------------------------------------------------------
10568: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10569: @subsection Object-Oriented Terminology
10570: @cindex object-oriented terminology
10571: @cindex terminology for object-oriented programming
10572: 
10573: This section is mainly for reference, so you don't have to understand
10574: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
10575: short:
10576: 
10577: @table @emph
10578: @cindex class
10579: @item class
10580: a data structure definition with some extras.
10581: 
10582: @cindex object
10583: @item object
10584: an instance of the data structure described by the class definition.
10585: 
10586: @cindex instance variables
10587: @item instance variables
10588: fields of the data structure.
10589: 
10590: @cindex selector
10591: @cindex method selector
10592: @cindex virtual function
10593: @item selector
10594: (or @emph{method selector}) a word (e.g.,
10595: @code{draw}) that performs an operation on a variety of data
10596: structures (classes). A selector describes @emph{what} operation to
10597: perform. In C++ terminology: a (pure) virtual function.
10598: 
10599: @cindex method
10600: @item method
10601: the concrete definition that performs the operation
10602: described by the selector for a specific class. A method specifies
10603: @emph{how} the operation is performed for a specific class.
10604: 
10605: @cindex selector invocation
10606: @cindex message send
10607: @cindex invoking a selector
10608: @item selector invocation
10609: a call of a selector. One argument of the call (the TOS (top-of-stack))
10610: is used for determining which method is used. In Smalltalk terminology:
10611: a message (consisting of the selector and the other arguments) is sent
10612: to the object.
10613: 
10614: @cindex receiving object
10615: @item receiving object
10616: the object used for determining the method executed by a selector
10617: invocation. In the @file{objects.fs} model, it is the object that is on
10618: the TOS when the selector is invoked. (@emph{Receiving} comes from
10619: the Smalltalk @emph{message} terminology.)
10620: 
10621: @cindex child class
10622: @cindex parent class
10623: @cindex inheritance
10624: @item child class
10625: a class that has (@emph{inherits}) all properties (instance variables,
10626: selectors, methods) from a @emph{parent class}. In Smalltalk
10627: terminology: The subclass inherits from the superclass. In C++
10628: terminology: The derived class inherits from the base class.
10629: 
10630: @end table
10631: 
10632: @c If you wonder about the message sending terminology, it comes from
10633: @c a time when each object had it's own task and objects communicated via
10634: @c message passing; eventually the Smalltalk developers realized that
10635: @c they can do most things through simple (indirect) calls. They kept the
10636: @c terminology.
10637: 
10638: @c --------------------------------------------------------------
10639: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10640: @subsection The @file{objects.fs} model
10641: @cindex objects
10642: @cindex object-oriented programming
10643: 
10644: @cindex @file{objects.fs}
10645: @cindex @file{oof.fs}
10646: 
10647: This section describes the @file{objects.fs} package. This material also
10648: has been published in M. Anton Ertl,
10649: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10650: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10651: 37--43.
10652: @c McKewan's and Zsoter's packages
10653: 
10654: This section assumes that you have read @ref{Structures}.
10655: 
10656: The techniques on which this model is based have been used to implement
10657: the parser generator, Gray, and have also been used in Gforth for
10658: implementing the various flavours of word lists (hashed or not,
10659: case-sensitive or not, special-purpose word lists for locals etc.).
10660: 
10661: 
10662: @menu
10663: * Properties of the Objects model::  
10664: * Basic Objects Usage::         
10665: * The Objects base class::      
10666: * Creating objects::            
10667: * Object-Oriented Programming Style::  
10668: * Class Binding::               
10669: * Method conveniences::         
10670: * Classes and Scoping::         
10671: * Dividing classes::            
10672: * Object Interfaces::           
10673: * Objects Implementation::      
10674: * Objects Glossary::            
10675: @end menu
10676: 
10677: Marcel Hendrix provided helpful comments on this section.
10678: 
10679: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10680: @subsubsection Properties of the @file{objects.fs} model
10681: @cindex @file{objects.fs} properties
10682: 
10683: @itemize @bullet
10684: @item
10685: It is straightforward to pass objects on the stack. Passing
10686: selectors on the stack is a little less convenient, but possible.
10687: 
10688: @item
10689: Objects are just data structures in memory, and are referenced by their
10690: address. You can create words for objects with normal defining words
10691: like @code{constant}. Likewise, there is no difference between instance
10692: variables that contain objects and those that contain other data.
10693: 
10694: @item
10695: Late binding is efficient and easy to use.
10696: 
10697: @item
10698: It avoids parsing, and thus avoids problems with state-smartness
10699: and reduced extensibility; for convenience there are a few parsing
10700: words, but they have non-parsing counterparts. There are also a few
10701: defining words that parse. This is hard to avoid, because all standard
10702: defining words parse (except @code{:noname}); however, such
10703: words are not as bad as many other parsing words, because they are not
10704: state-smart.
10705: 
10706: @item
10707: It does not try to incorporate everything. It does a few things and does
10708: them well (IMO). In particular, this model was not designed to support
10709: information hiding (although it has features that may help); you can use
10710: a separate package for achieving this.
10711: 
10712: @item
10713: It is layered; you don't have to learn and use all features to use this
10714: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10715: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10716: are optional and independent of each other.
10717: 
10718: @item
10719: An implementation in ANS Forth is available.
10720: 
10721: @end itemize
10722: 
10723: 
10724: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10725: @subsubsection Basic @file{objects.fs} Usage
10726: @cindex basic objects usage
10727: @cindex objects, basic usage
10728: 
10729: You can define a class for graphical objects like this:
10730: 
10731: @cindex @code{class} usage
10732: @cindex @code{end-class} usage
10733: @cindex @code{selector} usage
10734: @example
10735: object class \ "object" is the parent class
10736:   selector draw ( x y graphical -- )
10737: end-class graphical
10738: @end example
10739: 
10740: This code defines a class @code{graphical} with an
10741: operation @code{draw}.  We can perform the operation
10742: @code{draw} on any @code{graphical} object, e.g.:
10743: 
10744: @example
10745: 100 100 t-rex draw
10746: @end example
10747: 
10748: @noindent
10749: where @code{t-rex} is a word (say, a constant) that produces a
10750: graphical object.
10751: 
10752: @comment TODO add a 2nd operation eg perimeter.. and use for
10753: @comment a concrete example
10754: 
10755: @cindex abstract class
10756: How do we create a graphical object? With the present definitions,
10757: we cannot create a useful graphical object. The class
10758: @code{graphical} describes graphical objects in general, but not
10759: any concrete graphical object type (C++ users would call it an
10760: @emph{abstract class}); e.g., there is no method for the selector
10761: @code{draw} in the class @code{graphical}.
10762: 
10763: For concrete graphical objects, we define child classes of the
10764: class @code{graphical}, e.g.:
10765: 
10766: @cindex @code{overrides} usage
10767: @cindex @code{field} usage in class definition
10768: @example
10769: graphical class \ "graphical" is the parent class
10770:   cell% field circle-radius
10771: 
10772: :noname ( x y circle -- )
10773:   circle-radius @@ draw-circle ;
10774: overrides draw
10775: 
10776: :noname ( n-radius circle -- )
10777:   circle-radius ! ;
10778: overrides construct
10779: 
10780: end-class circle
10781: @end example
10782: 
10783: Here we define a class @code{circle} as a child of @code{graphical},
10784: with field @code{circle-radius} (which behaves just like a field
10785: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10786: for the selectors @code{draw} and @code{construct} (@code{construct} is
10787: defined in @code{object}, the parent class of @code{graphical}).
10788: 
10789: Now we can create a circle on the heap (i.e.,
10790: @code{allocate}d memory) with:
10791: 
10792: @cindex @code{heap-new} usage
10793: @example
10794: 50 circle heap-new constant my-circle
10795: @end example
10796: 
10797: @noindent
10798: @code{heap-new} invokes @code{construct}, thus
10799: initializing the field @code{circle-radius} with 50. We can draw
10800: this new circle at (100,100) with:
10801: 
10802: @example
10803: 100 100 my-circle draw
10804: @end example
10805: 
10806: @cindex selector invocation, restrictions
10807: @cindex class definition, restrictions
10808: Note: You can only invoke a selector if the object on the TOS
10809: (the receiving object) belongs to the class where the selector was
10810: defined or one of its descendents; e.g., you can invoke
10811: @code{draw} only for objects belonging to @code{graphical}
10812: or its descendents (e.g., @code{circle}).  Immediately before
10813: @code{end-class}, the search order has to be the same as
10814: immediately after @code{class}.
10815: 
10816: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10817: @subsubsection The @file{object.fs} base class
10818: @cindex @code{object} class
10819: 
10820: When you define a class, you have to specify a parent class.  So how do
10821: you start defining classes? There is one class available from the start:
10822: @code{object}. It is ancestor for all classes and so is the
10823: only class that has no parent. It has two selectors: @code{construct}
10824: and @code{print}.
10825: 
10826: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10827: @subsubsection Creating objects
10828: @cindex creating objects
10829: @cindex object creation
10830: @cindex object allocation options
10831: 
10832: @cindex @code{heap-new} discussion
10833: @cindex @code{dict-new} discussion
10834: @cindex @code{construct} discussion
10835: You can create and initialize an object of a class on the heap with
10836: @code{heap-new} ( ... class -- object ) and in the dictionary
10837: (allocation with @code{allot}) with @code{dict-new} (
10838: ... class -- object ). Both words invoke @code{construct}, which
10839: consumes the stack items indicated by "..." above.
10840: 
10841: @cindex @code{init-object} discussion
10842: @cindex @code{class-inst-size} discussion
10843: If you want to allocate memory for an object yourself, you can get its
10844: alignment and size with @code{class-inst-size 2@@} ( class --
10845: align size ). Once you have memory for an object, you can initialize
10846: it with @code{init-object} ( ... class object -- );
10847: @code{construct} does only a part of the necessary work.
10848: 
10849: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10850: @subsubsection Object-Oriented Programming Style
10851: @cindex object-oriented programming style
10852: @cindex programming style, object-oriented
10853: 
10854: This section is not exhaustive.
10855: 
10856: @cindex stack effects of selectors
10857: @cindex selectors and stack effects
10858: In general, it is a good idea to ensure that all methods for the
10859: same selector have the same stack effect: when you invoke a selector,
10860: you often have no idea which method will be invoked, so, unless all
10861: methods have the same stack effect, you will not know the stack effect
10862: of the selector invocation.
10863: 
10864: One exception to this rule is methods for the selector
10865: @code{construct}. We know which method is invoked, because we
10866: specify the class to be constructed at the same place. Actually, I
10867: defined @code{construct} as a selector only to give the users a
10868: convenient way to specify initialization. The way it is used, a
10869: mechanism different from selector invocation would be more natural
10870: (but probably would take more code and more space to explain).
10871: 
10872: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10873: @subsubsection Class Binding
10874: @cindex class binding
10875: @cindex early binding
10876: 
10877: @cindex late binding
10878: Normal selector invocations determine the method at run-time depending
10879: on the class of the receiving object. This run-time selection is called
10880: @i{late binding}.
10881: 
10882: Sometimes it's preferable to invoke a different method. For example,
10883: you might want to use the simple method for @code{print}ing
10884: @code{object}s instead of the possibly long-winded @code{print} method
10885: of the receiver class. You can achieve this by replacing the invocation
10886: of @code{print} with:
10887: 
10888: @cindex @code{[bind]} usage
10889: @example
10890: [bind] object print
10891: @end example
10892: 
10893: @noindent
10894: in compiled code or:
10895: 
10896: @cindex @code{bind} usage
10897: @example
10898: bind object print
10899: @end example
10900: 
10901: @cindex class binding, alternative to
10902: @noindent
10903: in interpreted code. Alternatively, you can define the method with a
10904: name (e.g., @code{print-object}), and then invoke it through the
10905: name. Class binding is just a (often more convenient) way to achieve
10906: the same effect; it avoids name clutter and allows you to invoke
10907: methods directly without naming them first.
10908: 
10909: @cindex superclass binding
10910: @cindex parent class binding
10911: A frequent use of class binding is this: When we define a method
10912: for a selector, we often want the method to do what the selector does
10913: in the parent class, and a little more. There is a special word for
10914: this purpose: @code{[parent]}; @code{[parent]
10915: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10916: selector}}, where @code{@emph{parent}} is the parent
10917: class of the current class. E.g., a method definition might look like:
10918: 
10919: @cindex @code{[parent]} usage
10920: @example
10921: :noname
10922:   dup [parent] foo \ do parent's foo on the receiving object
10923:   ... \ do some more
10924: ; overrides foo
10925: @end example
10926: 
10927: @cindex class binding as optimization
10928: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10929: March 1997), Andrew McKewan presents class binding as an optimization
10930: technique. I recommend not using it for this purpose unless you are in
10931: an emergency. Late binding is pretty fast with this model anyway, so the
10932: benefit of using class binding is small; the cost of using class binding
10933: where it is not appropriate is reduced maintainability.
10934: 
10935: While we are at programming style questions: You should bind
10936: selectors only to ancestor classes of the receiving object. E.g., say,
10937: you know that the receiving object is of class @code{foo} or its
10938: descendents; then you should bind only to @code{foo} and its
10939: ancestors.
10940: 
10941: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10942: @subsubsection Method conveniences
10943: @cindex method conveniences
10944: 
10945: In a method you usually access the receiving object pretty often.  If
10946: you define the method as a plain colon definition (e.g., with
10947: @code{:noname}), you may have to do a lot of stack
10948: gymnastics. To avoid this, you can define the method with @code{m:
10949: ... ;m}. E.g., you could define the method for
10950: @code{draw}ing a @code{circle} with
10951: 
10952: @cindex @code{this} usage
10953: @cindex @code{m:} usage
10954: @cindex @code{;m} usage
10955: @example
10956: m: ( x y circle -- )
10957:   ( x y ) this circle-radius @@ draw-circle ;m
10958: @end example
10959: 
10960: @cindex @code{exit} in @code{m: ... ;m}
10961: @cindex @code{exitm} discussion
10962: @cindex @code{catch} in @code{m: ... ;m}
10963: When this method is executed, the receiver object is removed from the
10964: stack; you can access it with @code{this} (admittedly, in this
10965: example the use of @code{m: ... ;m} offers no advantage). Note
10966: that I specify the stack effect for the whole method (i.e. including
10967: the receiver object), not just for the code between @code{m:}
10968: and @code{;m}. You cannot use @code{exit} in
10969: @code{m:...;m}; instead, use
10970: @code{exitm}.@footnote{Moreover, for any word that calls
10971: @code{catch} and was defined before loading
10972: @code{objects.fs}, you have to redefine it like I redefined
10973: @code{catch}: @code{: catch this >r catch r> to-this ;}}
10974: 
10975: @cindex @code{inst-var} usage
10976: You will frequently use sequences of the form @code{this
10977: @emph{field}} (in the example above: @code{this
10978: circle-radius}). If you use the field only in this way, you can
10979: define it with @code{inst-var} and eliminate the
10980: @code{this} before the field name. E.g., the @code{circle}
10981: class above could also be defined with:
10982: 
10983: @example
10984: graphical class
10985:   cell% inst-var radius
10986: 
10987: m: ( x y circle -- )
10988:   radius @@ draw-circle ;m
10989: overrides draw
10990: 
10991: m: ( n-radius circle -- )
10992:   radius ! ;m
10993: overrides construct
10994: 
10995: end-class circle
10996: @end example
10997: 
10998: @code{radius} can only be used in @code{circle} and its
10999: descendent classes and inside @code{m:...;m}.
11000: 
11001: @cindex @code{inst-value} usage
11002: You can also define fields with @code{inst-value}, which is
11003: to @code{inst-var} what @code{value} is to
11004: @code{variable}.  You can change the value of such a field with
11005: @code{[to-inst]}.  E.g., we could also define the class
11006: @code{circle} like this:
11007: 
11008: @example
11009: graphical class
11010:   inst-value radius
11011: 
11012: m: ( x y circle -- )
11013:   radius draw-circle ;m
11014: overrides draw
11015: 
11016: m: ( n-radius circle -- )
11017:   [to-inst] radius ;m
11018: overrides construct
11019: 
11020: end-class circle
11021: @end example
11022: 
11023: @c !! :m is easy to confuse with m:.  Another name would be better.
11024: 
11025: @c Finally, you can define named methods with @code{:m}.  One use of this
11026: @c feature is the definition of words that occur only in one class and are
11027: @c not intended to be overridden, but which still need method context
11028: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
11029: @c would be bound frequently, if defined anonymously.
11030: 
11031: 
11032: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
11033: @subsubsection Classes and Scoping
11034: @cindex classes and scoping
11035: @cindex scoping and classes
11036: 
11037: Inheritance is frequent, unlike structure extension. This exacerbates
11038: the problem with the field name convention (@pxref{Structure Naming
11039: Convention}): One always has to remember in which class the field was
11040: originally defined; changing a part of the class structure would require
11041: changes for renaming in otherwise unaffected code.
11042: 
11043: @cindex @code{inst-var} visibility
11044: @cindex @code{inst-value} visibility
11045: To solve this problem, I added a scoping mechanism (which was not in my
11046: original charter): A field defined with @code{inst-var} (or
11047: @code{inst-value}) is visible only in the class where it is defined and in
11048: the descendent classes of this class.  Using such fields only makes
11049: sense in @code{m:}-defined methods in these classes anyway.
11050: 
11051: This scoping mechanism allows us to use the unadorned field name,
11052: because name clashes with unrelated words become much less likely.
11053: 
11054: @cindex @code{protected} discussion
11055: @cindex @code{private} discussion
11056: Once we have this mechanism, we can also use it for controlling the
11057: visibility of other words: All words defined after
11058: @code{protected} are visible only in the current class and its
11059: descendents. @code{public} restores the compilation
11060: (i.e. @code{current}) word list that was in effect before. If you
11061: have several @code{protected}s without an intervening
11062: @code{public} or @code{set-current}, @code{public}
11063: will restore the compilation word list in effect before the first of
11064: these @code{protected}s.
11065: 
11066: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
11067: @subsubsection Dividing classes
11068: @cindex Dividing classes
11069: @cindex @code{methods}...@code{end-methods}
11070: 
11071: You may want to do the definition of methods separate from the
11072: definition of the class, its selectors, fields, and instance variables,
11073: i.e., separate the implementation from the definition.  You can do this
11074: in the following way:
11075: 
11076: @example
11077: graphical class
11078:   inst-value radius
11079: end-class circle
11080: 
11081: ... \ do some other stuff
11082: 
11083: circle methods \ now we are ready
11084: 
11085: m: ( x y circle -- )
11086:   radius draw-circle ;m
11087: overrides draw
11088: 
11089: m: ( n-radius circle -- )
11090:   [to-inst] radius ;m
11091: overrides construct
11092: 
11093: end-methods
11094: @end example
11095: 
11096: You can use several @code{methods}...@code{end-methods} sections.  The
11097: only things you can do to the class in these sections are: defining
11098: methods, and overriding the class's selectors.  You must not define new
11099: selectors or fields.
11100: 
11101: Note that you often have to override a selector before using it.  In
11102: particular, you usually have to override @code{construct} with a new
11103: method before you can invoke @code{heap-new} and friends.  E.g., you
11104: must not create a circle before the @code{overrides construct} sequence
11105: in the example above.
11106: 
11107: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
11108: @subsubsection Object Interfaces
11109: @cindex object interfaces
11110: @cindex interfaces for objects
11111: 
11112: In this model you can only call selectors defined in the class of the
11113: receiving objects or in one of its ancestors. If you call a selector
11114: with a receiving object that is not in one of these classes, the
11115: result is undefined; if you are lucky, the program crashes
11116: immediately.
11117: 
11118: @cindex selectors common to hardly-related classes
11119: Now consider the case when you want to have a selector (or several)
11120: available in two classes: You would have to add the selector to a
11121: common ancestor class, in the worst case to @code{object}. You
11122: may not want to do this, e.g., because someone else is responsible for
11123: this ancestor class.
11124: 
11125: The solution for this problem is interfaces. An interface is a
11126: collection of selectors. If a class implements an interface, the
11127: selectors become available to the class and its descendents. A class
11128: can implement an unlimited number of interfaces. For the problem
11129: discussed above, we would define an interface for the selector(s), and
11130: both classes would implement the interface.
11131: 
11132: As an example, consider an interface @code{storage} for
11133: writing objects to disk and getting them back, and a class
11134: @code{foo} that implements it. The code would look like this:
11135: 
11136: @cindex @code{interface} usage
11137: @cindex @code{end-interface} usage
11138: @cindex @code{implementation} usage
11139: @example
11140: interface
11141:   selector write ( file object -- )
11142:   selector read1 ( file object -- )
11143: end-interface storage
11144: 
11145: bar class
11146:   storage implementation
11147: 
11148: ... overrides write
11149: ... overrides read1
11150: ...
11151: end-class foo
11152: @end example
11153: 
11154: @noindent
11155: (I would add a word @code{read} @i{( file -- object )} that uses
11156: @code{read1} internally, but that's beyond the point illustrated
11157: here.)
11158: 
11159: Note that you cannot use @code{protected} in an interface; and
11160: of course you cannot define fields.
11161: 
11162: In the Neon model, all selectors are available for all classes;
11163: therefore it does not need interfaces. The price you pay in this model
11164: is slower late binding, and therefore, added complexity to avoid late
11165: binding.
11166: 
11167: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
11168: @subsubsection @file{objects.fs} Implementation
11169: @cindex @file{objects.fs} implementation
11170: 
11171: @cindex @code{object-map} discussion
11172: An object is a piece of memory, like one of the data structures
11173: described with @code{struct...end-struct}. It has a field
11174: @code{object-map} that points to the method map for the object's
11175: class.
11176: 
11177: @cindex method map
11178: @cindex virtual function table
11179: The @emph{method map}@footnote{This is Self terminology; in C++
11180: terminology: virtual function table.} is an array that contains the
11181: execution tokens (@i{xt}s) of the methods for the object's class. Each
11182: selector contains an offset into a method map.
11183: 
11184: @cindex @code{selector} implementation, class
11185: @code{selector} is a defining word that uses
11186: @code{CREATE} and @code{DOES>}. The body of the
11187: selector contains the offset; the @code{DOES>} action for a
11188: class selector is, basically:
11189: 
11190: @example
11191: ( object addr ) @@ over object-map @@ + @@ execute
11192: @end example
11193: 
11194: Since @code{object-map} is the first field of the object, it
11195: does not generate any code. As you can see, calling a selector has a
11196: small, constant cost.
11197: 
11198: @cindex @code{current-interface} discussion
11199: @cindex class implementation and representation
11200: A class is basically a @code{struct} combined with a method
11201: map. During the class definition the alignment and size of the class
11202: are passed on the stack, just as with @code{struct}s, so
11203: @code{field} can also be used for defining class
11204: fields. However, passing more items on the stack would be
11205: inconvenient, so @code{class} builds a data structure in memory,
11206: which is accessed through the variable
11207: @code{current-interface}. After its definition is complete, the
11208: class is represented on the stack by a pointer (e.g., as parameter for
11209: a child class definition).
11210: 
11211: A new class starts off with the alignment and size of its parent,
11212: and a copy of the parent's method map. Defining new fields extends the
11213: size and alignment; likewise, defining new selectors extends the
11214: method map. @code{overrides} just stores a new @i{xt} in the method
11215: map at the offset given by the selector.
11216: 
11217: @cindex class binding, implementation
11218: Class binding just gets the @i{xt} at the offset given by the selector
11219: from the class's method map and @code{compile,}s (in the case of
11220: @code{[bind]}) it.
11221: 
11222: @cindex @code{this} implementation
11223: @cindex @code{catch} and @code{this}
11224: @cindex @code{this} and @code{catch}
11225: I implemented @code{this} as a @code{value}. At the
11226: start of an @code{m:...;m} method the old @code{this} is
11227: stored to the return stack and restored at the end; and the object on
11228: the TOS is stored @code{TO this}. This technique has one
11229: disadvantage: If the user does not leave the method via
11230: @code{;m}, but via @code{throw} or @code{exit},
11231: @code{this} is not restored (and @code{exit} may
11232: crash). To deal with the @code{throw} problem, I have redefined
11233: @code{catch} to save and restore @code{this}; the same
11234: should be done with any word that can catch an exception. As for
11235: @code{exit}, I simply forbid it (as a replacement, there is
11236: @code{exitm}).
11237: 
11238: @cindex @code{inst-var} implementation
11239: @code{inst-var} is just the same as @code{field}, with
11240: a different @code{DOES>} action:
11241: @example
11242: @@ this +
11243: @end example
11244: Similar for @code{inst-value}.
11245: 
11246: @cindex class scoping implementation
11247: Each class also has a word list that contains the words defined with
11248: @code{inst-var} and @code{inst-value}, and its protected
11249: words. It also has a pointer to its parent. @code{class} pushes
11250: the word lists of the class and all its ancestors onto the search order stack,
11251: and @code{end-class} drops them.
11252: 
11253: @cindex interface implementation
11254: An interface is like a class without fields, parent and protected
11255: words; i.e., it just has a method map. If a class implements an
11256: interface, its method map contains a pointer to the method map of the
11257: interface. The positive offsets in the map are reserved for class
11258: methods, therefore interface map pointers have negative
11259: offsets. Interfaces have offsets that are unique throughout the
11260: system, unlike class selectors, whose offsets are only unique for the
11261: classes where the selector is available (invokable).
11262: 
11263: This structure means that interface selectors have to perform one
11264: indirection more than class selectors to find their method. Their body
11265: contains the interface map pointer offset in the class method map, and
11266: the method offset in the interface method map. The
11267: @code{does>} action for an interface selector is, basically:
11268: 
11269: @example
11270: ( object selector-body )
11271: 2dup selector-interface @@ ( object selector-body object interface-offset )
11272: swap object-map @@ + @@ ( object selector-body map )
11273: swap selector-offset @@ + @@ execute
11274: @end example
11275: 
11276: where @code{object-map} and @code{selector-offset} are
11277: first fields and generate no code.
11278: 
11279: As a concrete example, consider the following code:
11280: 
11281: @example
11282: interface
11283:   selector if1sel1
11284:   selector if1sel2
11285: end-interface if1
11286: 
11287: object class
11288:   if1 implementation
11289:   selector cl1sel1
11290:   cell% inst-var cl1iv1
11291: 
11292: ' m1 overrides construct
11293: ' m2 overrides if1sel1
11294: ' m3 overrides if1sel2
11295: ' m4 overrides cl1sel2
11296: end-class cl1
11297: 
11298: create obj1 object dict-new drop
11299: create obj2 cl1    dict-new drop
11300: @end example
11301: 
11302: The data structure created by this code (including the data structure
11303: for @code{object}) is shown in the
11304: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11305: @comment TODO add this diagram..
11306: 
11307: @node Objects Glossary,  , Objects Implementation, Objects
11308: @subsubsection @file{objects.fs} Glossary
11309: @cindex @file{objects.fs} Glossary
11310: 
11311: 
11312: doc---objects-bind
11313: doc---objects-<bind>
11314: doc---objects-bind'
11315: doc---objects-[bind]
11316: doc---objects-class
11317: doc---objects-class->map
11318: doc---objects-class-inst-size
11319: doc---objects-class-override!
11320: doc---objects-class-previous
11321: doc---objects-class>order
11322: doc---objects-construct
11323: doc---objects-current'
11324: doc---objects-[current]
11325: doc---objects-current-interface
11326: doc---objects-dict-new
11327: doc---objects-end-class
11328: doc---objects-end-class-noname
11329: doc---objects-end-interface
11330: doc---objects-end-interface-noname
11331: doc---objects-end-methods
11332: doc---objects-exitm
11333: doc---objects-heap-new
11334: doc---objects-implementation
11335: doc---objects-init-object
11336: doc---objects-inst-value
11337: doc---objects-inst-var
11338: doc---objects-interface
11339: doc---objects-m:
11340: doc---objects-:m
11341: doc---objects-;m
11342: doc---objects-method
11343: doc---objects-methods
11344: doc---objects-object
11345: doc---objects-overrides
11346: doc---objects-[parent]
11347: doc---objects-print
11348: doc---objects-protected
11349: doc---objects-public
11350: doc---objects-selector
11351: doc---objects-this
11352: doc---objects-<to-inst>
11353: doc---objects-[to-inst]
11354: doc---objects-to-this
11355: doc---objects-xt-new
11356: 
11357: 
11358: @c -------------------------------------------------------------
11359: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11360: @subsection The @file{oof.fs} model
11361: @cindex oof
11362: @cindex object-oriented programming
11363: 
11364: @cindex @file{objects.fs}
11365: @cindex @file{oof.fs}
11366: 
11367: This section describes the @file{oof.fs} package.
11368: 
11369: The package described in this section has been used in bigFORTH since 1991, and
11370: used for two large applications: a chromatographic system used to
11371: create new medicaments, and a graphic user interface library (MINOS).
11372: 
11373: You can find a description (in German) of @file{oof.fs} in @cite{Object
11374: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11375: 10(2), 1994.
11376: 
11377: @menu
11378: * Properties of the OOF model::  
11379: * Basic OOF Usage::             
11380: * The OOF base class::          
11381: * Class Declaration::           
11382: * Class Implementation::        
11383: @end menu
11384: 
11385: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11386: @subsubsection Properties of the @file{oof.fs} model
11387: @cindex @file{oof.fs} properties
11388: 
11389: @itemize @bullet
11390: @item
11391: This model combines object oriented programming with information
11392: hiding. It helps you writing large application, where scoping is
11393: necessary, because it provides class-oriented scoping.
11394: 
11395: @item
11396: Named objects, object pointers, and object arrays can be created,
11397: selector invocation uses the ``object selector'' syntax. Selector invocation
11398: to objects and/or selectors on the stack is a bit less convenient, but
11399: possible.
11400: 
11401: @item
11402: Selector invocation and instance variable usage of the active object is
11403: straightforward, since both make use of the active object.
11404: 
11405: @item
11406: Late binding is efficient and easy to use.
11407: 
11408: @item
11409: State-smart objects parse selectors. However, extensibility is provided
11410: using a (parsing) selector @code{postpone} and a selector @code{'}.
11411: 
11412: @item
11413: An implementation in ANS Forth is available.
11414: 
11415: @end itemize
11416: 
11417: 
11418: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11419: @subsubsection Basic @file{oof.fs} Usage
11420: @cindex @file{oof.fs} usage
11421: 
11422: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
11423: 
11424: You can define a class for graphical objects like this:
11425: 
11426: @cindex @code{class} usage
11427: @cindex @code{class;} usage
11428: @cindex @code{method} usage
11429: @example
11430: object class graphical \ "object" is the parent class
11431:   method draw ( x y -- )
11432: class;
11433: @end example
11434: 
11435: This code defines a class @code{graphical} with an
11436: operation @code{draw}.  We can perform the operation
11437: @code{draw} on any @code{graphical} object, e.g.:
11438: 
11439: @example
11440: 100 100 t-rex draw
11441: @end example
11442: 
11443: @noindent
11444: where @code{t-rex} is an object or object pointer, created with e.g.
11445: @code{graphical : t-rex}.
11446: 
11447: @cindex abstract class
11448: How do we create a graphical object? With the present definitions,
11449: we cannot create a useful graphical object. The class
11450: @code{graphical} describes graphical objects in general, but not
11451: any concrete graphical object type (C++ users would call it an
11452: @emph{abstract class}); e.g., there is no method for the selector
11453: @code{draw} in the class @code{graphical}.
11454: 
11455: For concrete graphical objects, we define child classes of the
11456: class @code{graphical}, e.g.:
11457: 
11458: @example
11459: graphical class circle \ "graphical" is the parent class
11460:   cell var circle-radius
11461: how:
11462:   : draw ( x y -- )
11463:     circle-radius @@ draw-circle ;
11464: 
11465:   : init ( n-radius -- )
11466:     circle-radius ! ;
11467: class;
11468: @end example
11469: 
11470: Here we define a class @code{circle} as a child of @code{graphical},
11471: with a field @code{circle-radius}; it defines new methods for the
11472: selectors @code{draw} and @code{init} (@code{init} is defined in
11473: @code{object}, the parent class of @code{graphical}).
11474: 
11475: Now we can create a circle in the dictionary with:
11476: 
11477: @example
11478: 50 circle : my-circle
11479: @end example
11480: 
11481: @noindent
11482: @code{:} invokes @code{init}, thus initializing the field
11483: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11484: with:
11485: 
11486: @example
11487: 100 100 my-circle draw
11488: @end example
11489: 
11490: @cindex selector invocation, restrictions
11491: @cindex class definition, restrictions
11492: Note: You can only invoke a selector if the receiving object belongs to
11493: the class where the selector was defined or one of its descendents;
11494: e.g., you can invoke @code{draw} only for objects belonging to
11495: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11496: mechanism will check if you try to invoke a selector that is not
11497: defined in this class hierarchy, so you'll get an error at compilation
11498: time.
11499: 
11500: 
11501: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11502: @subsubsection The @file{oof.fs} base class
11503: @cindex @file{oof.fs} base class
11504: 
11505: When you define a class, you have to specify a parent class.  So how do
11506: you start defining classes? There is one class available from the start:
11507: @code{object}. You have to use it as ancestor for all classes. It is the
11508: only class that has no parent. Classes are also objects, except that
11509: they don't have instance variables; class manipulation such as
11510: inheritance or changing definitions of a class is handled through
11511: selectors of the class @code{object}.
11512: 
11513: @code{object} provides a number of selectors:
11514: 
11515: @itemize @bullet
11516: @item
11517: @code{class} for subclassing, @code{definitions} to add definitions
11518: later on, and @code{class?} to get type informations (is the class a
11519: subclass of the class passed on the stack?).
11520: 
11521: doc---object-class
11522: doc---object-definitions
11523: doc---object-class?
11524: 
11525: 
11526: @item
11527: @code{init} and @code{dispose} as constructor and destructor of the
11528: object. @code{init} is invocated after the object's memory is allocated,
11529: while @code{dispose} also handles deallocation. Thus if you redefine
11530: @code{dispose}, you have to call the parent's dispose with @code{super
11531: dispose}, too.
11532: 
11533: doc---object-init
11534: doc---object-dispose
11535: 
11536: 
11537: @item
11538: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11539: @code{[]} to create named and unnamed objects and object arrays or
11540: object pointers.
11541: 
11542: doc---object-new
11543: doc---object-new[]
11544: doc---object-:
11545: doc---object-ptr
11546: doc---object-asptr
11547: doc---object-[]
11548: 
11549: 
11550: @item
11551: @code{::} and @code{super} for explicit scoping. You should use explicit
11552: scoping only for super classes or classes with the same set of instance
11553: variables. Explicitly-scoped selectors use early binding.
11554: 
11555: doc---object-::
11556: doc---object-super
11557: 
11558: 
11559: @item
11560: @code{self} to get the address of the object
11561: 
11562: doc---object-self
11563: 
11564: 
11565: @item
11566: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11567: pointers and instance defers.
11568: 
11569: doc---object-bind
11570: doc---object-bound
11571: doc---object-link
11572: doc---object-is
11573: 
11574: 
11575: @item
11576: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11577: form the stack, and @code{postpone} to generate selector invocation code.
11578: 
11579: doc---object-'
11580: doc---object-postpone
11581: 
11582: 
11583: @item
11584: @code{with} and @code{endwith} to select the active object from the
11585: stack, and enable its scope. Using @code{with} and @code{endwith}
11586: also allows you to create code using selector @code{postpone} without being
11587: trapped by the state-smart objects.
11588: 
11589: doc---object-with
11590: doc---object-endwith
11591: 
11592: 
11593: @end itemize
11594: 
11595: @node Class Declaration, Class Implementation, The OOF base class, OOF
11596: @subsubsection Class Declaration
11597: @cindex class declaration
11598: 
11599: @itemize @bullet
11600: @item
11601: Instance variables
11602: 
11603: doc---oof-var
11604: 
11605: 
11606: @item
11607: Object pointers
11608: 
11609: doc---oof-ptr
11610: doc---oof-asptr
11611: 
11612: 
11613: @item
11614: Instance defers
11615: 
11616: doc---oof-defer
11617: 
11618: 
11619: @item
11620: Method selectors
11621: 
11622: doc---oof-early
11623: doc---oof-method
11624: 
11625: 
11626: @item
11627: Class-wide variables
11628: 
11629: doc---oof-static
11630: 
11631: 
11632: @item
11633: End declaration
11634: 
11635: doc---oof-how:
11636: doc---oof-class;
11637: 
11638: 
11639: @end itemize
11640: 
11641: @c -------------------------------------------------------------
11642: @node Class Implementation,  , Class Declaration, OOF
11643: @subsubsection Class Implementation
11644: @cindex class implementation
11645: 
11646: @c -------------------------------------------------------------
11647: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11648: @subsection The @file{mini-oof.fs} model
11649: @cindex mini-oof
11650: 
11651: Gforth's third object oriented Forth package is a 12-liner. It uses a
11652: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
11653: and reduces to the bare minimum of features. This is based on a posting
11654: of Bernd Paysan in comp.lang.forth.
11655: 
11656: @menu
11657: * Basic Mini-OOF Usage::        
11658: * Mini-OOF Example::            
11659: * Mini-OOF Implementation::     
11660: @end menu
11661: 
11662: @c -------------------------------------------------------------
11663: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11664: @subsubsection Basic @file{mini-oof.fs} Usage
11665: @cindex mini-oof usage
11666: 
11667: There is a base class (@code{class}, which allocates one cell for the
11668: object pointer) plus seven other words: to define a method, a variable,
11669: a class; to end a class, to resolve binding, to allocate an object and
11670: to compile a class method.
11671: @comment TODO better description of the last one
11672: 
11673: 
11674: doc-object
11675: doc-method
11676: doc-var
11677: doc-class
11678: doc-end-class
11679: doc-defines
11680: doc-new
11681: doc-::
11682: 
11683: 
11684: 
11685: @c -------------------------------------------------------------
11686: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11687: @subsubsection Mini-OOF Example
11688: @cindex mini-oof example
11689: 
11690: A short example shows how to use this package. This example, in slightly
11691: extended form, is supplied as @file{moof-exm.fs}
11692: @comment TODO could flesh this out with some comments from the Forthwrite article
11693: 
11694: @example
11695: object class
11696:   method init
11697:   method draw
11698: end-class graphical
11699: @end example
11700: 
11701: This code defines a class @code{graphical} with an
11702: operation @code{draw}.  We can perform the operation
11703: @code{draw} on any @code{graphical} object, e.g.:
11704: 
11705: @example
11706: 100 100 t-rex draw
11707: @end example
11708: 
11709: where @code{t-rex} is an object or object pointer, created with e.g.
11710: @code{graphical new Constant t-rex}.
11711: 
11712: For concrete graphical objects, we define child classes of the
11713: class @code{graphical}, e.g.:
11714: 
11715: @example
11716: graphical class
11717:   cell var circle-radius
11718: end-class circle \ "graphical" is the parent class
11719: 
11720: :noname ( x y -- )
11721:   circle-radius @@ draw-circle ; circle defines draw
11722: :noname ( r -- )
11723:   circle-radius ! ; circle defines init
11724: @end example
11725: 
11726: There is no implicit init method, so we have to define one. The creation
11727: code of the object now has to call init explicitely.
11728: 
11729: @example
11730: circle new Constant my-circle
11731: 50 my-circle init
11732: @end example
11733: 
11734: It is also possible to add a function to create named objects with
11735: automatic call of @code{init}, given that all objects have @code{init}
11736: on the same place:
11737: 
11738: @example
11739: : new: ( .. o "name" -- )
11740:     new dup Constant init ;
11741: 80 circle new: large-circle
11742: @end example
11743: 
11744: We can draw this new circle at (100,100) with:
11745: 
11746: @example
11747: 100 100 my-circle draw
11748: @end example
11749: 
11750: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
11751: @subsubsection @file{mini-oof.fs} Implementation
11752: 
11753: Object-oriented systems with late binding typically use a
11754: ``vtable''-approach: the first variable in each object is a pointer to a
11755: table, which contains the methods as function pointers. The vtable
11756: may also contain other information.
11757: 
11758: So first, let's declare selectors:
11759: 
11760: @example
11761: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
11762:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11763: @end example
11764: 
11765: During selector declaration, the number of selectors and instance
11766: variables is on the stack (in address units). @code{method} creates one
11767: selector and increments the selector number. To execute a selector, it
11768: takes the object, fetches the vtable pointer, adds the offset, and
11769: executes the method @i{xt} stored there. Each selector takes the object
11770: it is invoked with as top of stack parameter; it passes the parameters
11771: (including the object) unchanged to the appropriate method which should
11772: consume that object.
11773: 
11774: Now, we also have to declare instance variables
11775: 
11776: @example
11777: : var ( m v size "name" -- m v' ) Create  over , +
11778:   DOES> ( o -- addr ) @@ + ;
11779: @end example
11780: 
11781: As before, a word is created with the current offset. Instance
11782: variables can have different sizes (cells, floats, doubles, chars), so
11783: all we do is take the size and add it to the offset. If your machine
11784: has alignment restrictions, put the proper @code{aligned} or
11785: @code{faligned} before the variable, to adjust the variable
11786: offset. That's why it is on the top of stack.
11787: 
11788: We need a starting point (the base object) and some syntactic sugar:
11789: 
11790: @example
11791: Create object  1 cells , 2 cells ,
11792: : class ( class -- class selectors vars ) dup 2@@ ;
11793: @end example
11794: 
11795: For inheritance, the vtable of the parent object has to be
11796: copied when a new, derived class is declared. This gives all the
11797: methods of the parent class, which can be overridden, though.
11798: 
11799: @example
11800: : end-class  ( class selectors vars "name" -- )
11801:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11802:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
11803: @end example
11804: 
11805: The first line creates the vtable, initialized with
11806: @code{noop}s. The second line is the inheritance mechanism, it
11807: copies the xts from the parent vtable.
11808: 
11809: We still have no way to define new methods, let's do that now:
11810: 
11811: @example
11812: : defines ( xt class "name" -- ) ' >body @@ + ! ;
11813: @end example
11814: 
11815: To allocate a new object, we need a word, too:
11816: 
11817: @example
11818: : new ( class -- o )  here over @@ allot swap over ! ;
11819: @end example
11820: 
11821: Sometimes derived classes want to access the method of the
11822: parent object. There are two ways to achieve this with Mini-OOF:
11823: first, you could use named words, and second, you could look up the
11824: vtable of the parent object.
11825: 
11826: @example
11827: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11828: @end example
11829: 
11830: 
11831: Nothing can be more confusing than a good example, so here is
11832: one. First let's declare a text object (called
11833: @code{button}), that stores text and position:
11834: 
11835: @example
11836: object class
11837:   cell var text
11838:   cell var len
11839:   cell var x
11840:   cell var y
11841:   method init
11842:   method draw
11843: end-class button
11844: @end example
11845: 
11846: @noindent
11847: Now, implement the two methods, @code{draw} and @code{init}:
11848: 
11849: @example
11850: :noname ( o -- )
11851:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
11852:  button defines draw
11853: :noname ( addr u o -- )
11854:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11855:  button defines init
11856: @end example
11857: 
11858: @noindent
11859: To demonstrate inheritance, we define a class @code{bold-button}, with no
11860: new data and no new selectors:
11861: 
11862: @example
11863: button class
11864: end-class bold-button
11865: 
11866: : bold   27 emit ." [1m" ;
11867: : normal 27 emit ." [0m" ;
11868: @end example
11869: 
11870: @noindent
11871: The class @code{bold-button} has a different draw method to
11872: @code{button}, but the new method is defined in terms of the draw method
11873: for @code{button}:
11874: 
11875: @example
11876: :noname bold [ button :: draw ] normal ; bold-button defines draw
11877: @end example
11878: 
11879: @noindent
11880: Finally, create two objects and apply selectors:
11881: 
11882: @example
11883: button new Constant foo
11884: s" thin foo" foo init
11885: page
11886: foo draw
11887: bold-button new Constant bar
11888: s" fat bar" bar init
11889: 1 bar y !
11890: bar draw
11891: @end example
11892: 
11893: 
11894: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
11895: @subsection Comparison with other object models
11896: @cindex comparison of object models
11897: @cindex object models, comparison
11898: 
11899: Many object-oriented Forth extensions have been proposed (@cite{A survey
11900: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11901: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11902: relation of the object models described here to two well-known and two
11903: closely-related (by the use of method maps) models.  Andras Zsoter
11904: helped us with this section.
11905: 
11906: @cindex Neon model
11907: The most popular model currently seems to be the Neon model (see
11908: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11909: 1997) by Andrew McKewan) but this model has a number of limitations
11910: @footnote{A longer version of this critique can be
11911: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11912: Dimensions, May 1997) by Anton Ertl.}:
11913: 
11914: @itemize @bullet
11915: @item
11916: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11917: to pass objects on the stack.
11918: 
11919: @item
11920: It requires that the selector parses the input stream (at
11921: compile time); this leads to reduced extensibility and to bugs that are
11922: hard to find.
11923: 
11924: @item
11925: It allows using every selector on every object; this eliminates the
11926: need for interfaces, but makes it harder to create efficient
11927: implementations.
11928: @end itemize
11929: 
11930: @cindex Pountain's object-oriented model
11931: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11932: Press, London, 1987) by Dick Pountain. However, it is not really about
11933: object-oriented programming, because it hardly deals with late
11934: binding. Instead, it focuses on features like information hiding and
11935: overloading that are characteristic of modular languages like Ada (83).
11936: 
11937: @cindex Zsoter's object-oriented model
11938: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11939: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11940: describes a model that makes heavy use of an active object (like
11941: @code{this} in @file{objects.fs}): The active object is not only used
11942: for accessing all fields, but also specifies the receiving object of
11943: every selector invocation; you have to change the active object
11944: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11945: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11946: the method entry point is unnecessary with Zsoter's model, because the
11947: receiving object is the active object already. On the other hand, the
11948: explicit change is absolutely necessary in that model, because otherwise
11949: no one could ever change the active object. An ANS Forth implementation
11950: of this model is available through
11951: @uref{http://www.forth.org/oopf.html}.
11952: 
11953: @cindex @file{oof.fs}, differences to other models
11954: The @file{oof.fs} model combines information hiding and overloading
11955: resolution (by keeping names in various word lists) with object-oriented
11956: programming. It sets the active object implicitly on method entry, but
11957: also allows explicit changing (with @code{>o...o>} or with
11958: @code{with...endwith}). It uses parsing and state-smart objects and
11959: classes for resolving overloading and for early binding: the object or
11960: class parses the selector and determines the method from this. If the
11961: selector is not parsed by an object or class, it performs a call to the
11962: selector for the active object (late binding), like Zsoter's model.
11963: Fields are always accessed through the active object. The big
11964: disadvantage of this model is the parsing and the state-smartness, which
11965: reduces extensibility and increases the opportunities for subtle bugs;
11966: essentially, you are only safe if you never tick or @code{postpone} an
11967: object or class (Bernd disagrees, but I (Anton) am not convinced).
11968: 
11969: @cindex @file{mini-oof.fs}, differences to other models
11970: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11971: version of the @file{objects.fs} model, but syntactically it is a
11972: mixture of the @file{objects.fs} and @file{oof.fs} models.
11973: 
11974: 
11975: @c -------------------------------------------------------------
11976: @node Programming Tools, C Interface, Object-oriented Forth, Words
11977: @section Programming Tools
11978: @cindex programming tools
11979: 
11980: @c !! move this and assembler down below OO stuff.
11981: 
11982: @menu
11983: * Examining::                   Data and Code.
11984: * Forgetting words::            Usually before reloading.
11985: * Debugging::                   Simple and quick.
11986: * Assertions::                  Making your programs self-checking.
11987: * Singlestep Debugger::         Executing your program word by word.
11988: @end menu
11989: 
11990: @node Examining, Forgetting words, Programming Tools, Programming Tools
11991: @subsection Examining data and code
11992: @cindex examining data and code
11993: @cindex data examination
11994: @cindex code examination
11995: 
11996: The following words inspect the stack non-destructively:
11997: 
11998: doc-.s
11999: doc-f.s
12000: doc-maxdepth-.s
12001: 
12002: There is a word @code{.r} but it does @i{not} display the return stack!
12003: It is used for formatted numeric output (@pxref{Simple numeric output}).
12004: 
12005: doc-depth
12006: doc-fdepth
12007: doc-clearstack
12008: doc-clearstacks
12009: 
12010: The following words inspect memory.
12011: 
12012: doc-?
12013: doc-dump
12014: 
12015: And finally, @code{see} allows to inspect code:
12016: 
12017: doc-see
12018: doc-xt-see
12019: doc-simple-see
12020: doc-simple-see-range
12021: doc-see-code
12022: doc-see-code-range
12023: 
12024: @node Forgetting words, Debugging, Examining, Programming Tools
12025: @subsection Forgetting words
12026: @cindex words, forgetting
12027: @cindex forgeting words
12028: 
12029: @c  anton: other, maybe better places for this subsection: Defining Words;
12030: @c  Dictionary allocation.  At least a reference should be there.
12031: 
12032: Forth allows you to forget words (and everything that was alloted in the
12033: dictonary after them) in a LIFO manner.
12034: 
12035: doc-marker
12036: 
12037: The most common use of this feature is during progam development: when
12038: you change a source file, forget all the words it defined and load it
12039: again (since you also forget everything defined after the source file
12040: was loaded, you have to reload that, too).  Note that effects like
12041: storing to variables and destroyed system words are not undone when you
12042: forget words.  With a system like Gforth, that is fast enough at
12043: starting up and compiling, I find it more convenient to exit and restart
12044: Gforth, as this gives me a clean slate.
12045: 
12046: Here's an example of using @code{marker} at the start of a source file
12047: that you are debugging; it ensures that you only ever have one copy of
12048: the file's definitions compiled at any time:
12049: 
12050: @example
12051: [IFDEF] my-code
12052:     my-code
12053: [ENDIF]
12054: 
12055: marker my-code
12056: init-included-files
12057: 
12058: \ .. definitions start here
12059: \ .
12060: \ .
12061: \ end
12062: @end example
12063: 
12064: 
12065: @node Debugging, Assertions, Forgetting words, Programming Tools
12066: @subsection Debugging
12067: @cindex debugging
12068: 
12069: Languages with a slow edit/compile/link/test development loop tend to
12070: require sophisticated tracing/stepping debuggers to facilate debugging.
12071: 
12072: A much better (faster) way in fast-compiling languages is to add
12073: printing code at well-selected places, let the program run, look at
12074: the output, see where things went wrong, add more printing code, etc.,
12075: until the bug is found.
12076: 
12077: The simple debugging aids provided in @file{debugs.fs}
12078: are meant to support this style of debugging.
12079: 
12080: The word @code{~~} prints debugging information (by default the source
12081: location and the stack contents). It is easy to insert. If you use Emacs
12082: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
12083: query-replace them with nothing). The deferred words
12084: @code{printdebugdata} and @code{.debugline} control the output of
12085: @code{~~}. The default source location output format works well with
12086: Emacs' compilation mode, so you can step through the program at the
12087: source level using @kbd{C-x `} (the advantage over a stepping debugger
12088: is that you can step in any direction and you know where the crash has
12089: happened or where the strange data has occurred).
12090: 
12091: doc-~~
12092: doc-printdebugdata
12093: doc-.debugline
12094: doc-debug-fid
12095: 
12096: @cindex filenames in @code{~~} output
12097: @code{~~} (and assertions) will usually print the wrong file name if a
12098: marker is executed in the same file after their occurance.  They will
12099: print @samp{*somewhere*} as file name if a marker is executed in the
12100: same file before their occurance.
12101: 
12102: 
12103: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
12104: @subsection Assertions
12105: @cindex assertions
12106: 
12107: It is a good idea to make your programs self-checking, especially if you
12108: make an assumption that may become invalid during maintenance (for
12109: example, that a certain field of a data structure is never zero). Gforth
12110: supports @dfn{assertions} for this purpose. They are used like this:
12111: 
12112: @example
12113: assert( @i{flag} )
12114: @end example
12115: 
12116: The code between @code{assert(} and @code{)} should compute a flag, that
12117: should be true if everything is alright and false otherwise. It should
12118: not change anything else on the stack. The overall stack effect of the
12119: assertion is @code{( -- )}. E.g.
12120: 
12121: @example
12122: assert( 1 1 + 2 = ) \ what we learn in school
12123: assert( dup 0<> ) \ assert that the top of stack is not zero
12124: assert( false ) \ this code should not be reached
12125: @end example
12126: 
12127: The need for assertions is different at different times. During
12128: debugging, we want more checking, in production we sometimes care more
12129: for speed. Therefore, assertions can be turned off, i.e., the assertion
12130: becomes a comment. Depending on the importance of an assertion and the
12131: time it takes to check it, you may want to turn off some assertions and
12132: keep others turned on. Gforth provides several levels of assertions for
12133: this purpose:
12134: 
12135: 
12136: doc-assert0(
12137: doc-assert1(
12138: doc-assert2(
12139: doc-assert3(
12140: doc-assert(
12141: doc-)
12142: 
12143: 
12144: The variable @code{assert-level} specifies the highest assertions that
12145: are turned on. I.e., at the default @code{assert-level} of one,
12146: @code{assert0(} and @code{assert1(} assertions perform checking, while
12147: @code{assert2(} and @code{assert3(} assertions are treated as comments.
12148: 
12149: The value of @code{assert-level} is evaluated at compile-time, not at
12150: run-time. Therefore you cannot turn assertions on or off at run-time;
12151: you have to set the @code{assert-level} appropriately before compiling a
12152: piece of code. You can compile different pieces of code at different
12153: @code{assert-level}s (e.g., a trusted library at level 1 and
12154: newly-written code at level 3).
12155: 
12156: 
12157: doc-assert-level
12158: 
12159: 
12160: If an assertion fails, a message compatible with Emacs' compilation mode
12161: is produced and the execution is aborted (currently with @code{ABORT"}.
12162: If there is interest, we will introduce a special throw code. But if you
12163: intend to @code{catch} a specific condition, using @code{throw} is
12164: probably more appropriate than an assertion).
12165: 
12166: @cindex filenames in assertion output
12167: Assertions (and @code{~~}) will usually print the wrong file name if a
12168: marker is executed in the same file after their occurance.  They will
12169: print @samp{*somewhere*} as file name if a marker is executed in the
12170: same file before their occurance.
12171: 
12172: Definitions in ANS Forth for these assertion words are provided
12173: in @file{compat/assert.fs}.
12174: 
12175: 
12176: @node Singlestep Debugger,  , Assertions, Programming Tools
12177: @subsection Singlestep Debugger
12178: @cindex singlestep Debugger
12179: @cindex debugging Singlestep
12180: 
12181: The singlestep debugger works only with the engine @code{gforth-itc}.
12182: 
12183: When you create a new word there's often the need to check whether it
12184: behaves correctly or not. You can do this by typing @code{dbg
12185: badword}. A debug session might look like this:
12186: 
12187: @example
12188: : badword 0 DO i . LOOP ;  ok
12189: 2 dbg badword 
12190: : badword  
12191: Scanning code...
12192: 
12193: Nesting debugger ready!
12194: 
12195: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
12196: 400D4740  8049F68 DO             -> [ 0 ] 
12197: 400D4744  804A0C8 i              -> [ 1 ] 00000 
12198: 400D4748 400C5E60 .              -> 0 [ 0 ] 
12199: 400D474C  8049D0C LOOP           -> [ 0 ] 
12200: 400D4744  804A0C8 i              -> [ 1 ] 00001 
12201: 400D4748 400C5E60 .              -> 1 [ 0 ] 
12202: 400D474C  8049D0C LOOP           -> [ 0 ] 
12203: 400D4758  804B384 ;              ->  ok
12204: @end example
12205: 
12206: Each line displayed is one step. You always have to hit return to
12207: execute the next word that is displayed. If you don't want to execute
12208: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12209: an overview what keys are available:
12210: 
12211: @table @i
12212: 
12213: @item @key{RET}
12214: Next; Execute the next word.
12215: 
12216: @item n
12217: Nest; Single step through next word.
12218: 
12219: @item u
12220: Unnest; Stop debugging and execute rest of word. If we got to this word
12221: with nest, continue debugging with the calling word.
12222: 
12223: @item d
12224: Done; Stop debugging and execute rest.
12225: 
12226: @item s
12227: Stop; Abort immediately.
12228: 
12229: @end table
12230: 
12231: Debugging large application with this mechanism is very difficult, because
12232: you have to nest very deeply into the program before the interesting part
12233: begins. This takes a lot of time. 
12234: 
12235: To do it more directly put a @code{BREAK:} command into your source code.
12236: When program execution reaches @code{BREAK:} the single step debugger is
12237: invoked and you have all the features described above.
12238: 
12239: If you have more than one part to debug it is useful to know where the
12240: program has stopped at the moment. You can do this by the 
12241: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12242: string is typed out when the ``breakpoint'' is reached.
12243: 
12244: 
12245: doc-dbg
12246: doc-break:
12247: doc-break"
12248: 
12249: @c ------------------------------------------------------------
12250: @node C Interface, Assembler and Code Words, Programming Tools, Words
12251: @section C Interface
12252: @cindex C interface
12253: @cindex foreign language interface
12254: @cindex interface to C functions
12255: 
12256: Note that the C interface is not yet complete; callbacks are missing,
12257: as well as a way of declaring structs, unions, and their fields.
12258: 
12259: @menu
12260: * Calling C Functions::         
12261: * Declaring C Functions::       
12262: * Calling C function pointers::  
12263: * Defining library interfaces::  
12264: * Declaring OS-level libraries::  
12265: * Callbacks::                   
12266: * C interface internals::       
12267: * Low-Level C Interface Words::  
12268: @end menu
12269: 
12270: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
12271: @subsection Calling C functions
12272: @cindex C functions, calls to
12273: @cindex calling C functions
12274: 
12275: Once a C function is declared (see @pxref{Declaring C Functions}), you
12276: can call it as follows: You push the arguments on the stack(s), and
12277: then call the word for the C function.  The arguments have to be
12278: pushed in the same order as the arguments appear in the C
12279: documentation (i.e., the first argument is deepest on the stack).
12280: Integer and pointer arguments have to be pushed on the data stack,
12281: floating-point arguments on the FP stack; these arguments are consumed
12282: by the called C function.
12283: 
12284: On returning from the C function, the return value, if any, resides on
12285: the appropriate stack: an integer return value is pushed on the data
12286: stack, an FP return value on the FP stack, and a void return value
12287: results in not pushing anything.  Note that most C functions have a
12288: return value, even if that is often not used in C; in Forth, you have
12289: to @code{drop} this return value explicitly if you do not use it.
12290: 
12291: The C interface automatically converts between the C type and the
12292: Forth type as necessary, on a best-effort basis (in some cases, there
12293: may be some loss).
12294: 
12295: As an example, consider the POSIX function @code{lseek()}:
12296: 
12297: @example
12298: off_t lseek(int fd, off_t offset, int whence);
12299: @end example
12300: 
12301: This function takes three integer arguments, and returns an integer
12302: argument, so a Forth call for setting the current file offset to the
12303: start of the file could look like this:
12304: 
12305: @example
12306: fd @@ 0 SEEK_SET lseek -1 = if
12307:   ... \ error handling
12308: then
12309: @end example
12310: 
12311: You might be worried that an @code{off_t} does not fit into a cell, so
12312: you could not pass larger offsets to lseek, and might get only a part
12313: of the return values.  In that case, in your declaration of the
12314: function (@pxref{Declaring C Functions}) you should declare it to use
12315: double-cells for the off_t argument and return value, and maybe give
12316: the resulting Forth word a different name, like @code{dlseek}; the
12317: result could be called like this:
12318: 
12319: @example
12320: fd @@ 0. SEEK_SET dlseek -1. d= if
12321:   ... \ error handling
12322: then
12323: @end example
12324: 
12325: Passing and returning structs or unions is currently not supported by
12326: our interface@footnote{If you know the calling convention of your C
12327: compiler, you usually can call such functions in some way, but that
12328: way is usually not portable between platforms, and sometimes not even
12329: between C compilers.}.
12330: 
12331: Calling functions with a variable number of arguments (@emph{variadic}
12332: functions, e.g., @code{printf()}) is only supported by having you
12333: declare one function-calling word for each argument pattern, and
12334: calling the appropriate word for the desired pattern.
12335: 
12336: 
12337: 
12338: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
12339: @subsection Declaring C Functions
12340: @cindex C functions, declarations
12341: @cindex declaring C functions
12342: 
12343: Before you can call @code{lseek} or @code{dlseek}, you have to declare
12344: it.  The declaration consists of two parts: 
12345: 
12346: @table @b
12347: 
12348: @item The C part
12349: is the C declaration of the function, or more typically and portably,
12350: a C-style @code{#include} of a file that contains the declaration of
12351: the C function.
12352: 
12353: @item The Forth part
12354: declares the Forth types of the parameters and the Forth word name
12355: corresponding to the C function.
12356: 
12357: @end table
12358: 
12359: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12360: declarations are:
12361: 
12362: @example
12363: \c #define _FILE_OFFSET_BITS 64
12364: \c #include <sys/types.h>
12365: \c #include <unistd.h>
12366: c-function lseek lseek n n n -- n
12367: c-function dlseek lseek n d n -- d
12368: @end example
12369: 
12370: The C part of the declarations is prefixed by @code{\c}, and the rest
12371: of the line is ordinary C code.  You can use as many lines of C
12372: declarations as you like, and they are visible for all further
12373: function declarations.
12374: 
12375: The Forth part declares each interface word with @code{c-function},
12376: followed by the Forth name of the word, the C name of the called
12377: function, and the stack effect of the word.  The stack effect contains
12378: an arbitrary number of types of parameters, then @code{--}, and then
12379: exactly one type for the return value.  The possible types are:
12380: 
12381: @table @code
12382: 
12383: @item n
12384: single-cell integer
12385: 
12386: @item a
12387: address (single-cell)
12388: 
12389: @item d
12390: double-cell integer
12391: 
12392: @item r
12393: floating-point value
12394: 
12395: @item func
12396: C function pointer
12397: 
12398: @item void
12399: no value (used as return type for void functions)
12400: 
12401: @end table
12402: 
12403: @cindex variadic C functions
12404: 
12405: To deal with variadic C functions, you can declare one Forth word for
12406: every pattern you want to use, e.g.:
12407: 
12408: @example
12409: \c #include <stdio.h>
12410: c-function printf-nr printf a n r -- n
12411: c-function printf-rn printf a r n -- n
12412: @end example
12413: 
12414: Note that with C functions declared as variadic (or if you don't
12415: provide a prototype), the C interface has no C type to convert to, so
12416: no automatic conversion happens, which may lead to portability
12417: problems in some cases.  In such cases you can perform the conversion
12418: explicitly on the C level, e.g., as follows:
12419: 
12420: @example
12421: \c #define printfll(s,ll) printf(s,(long long)ll)
12422: c-function printfll printfll a n -- n
12423: @end example
12424: 
12425: Here, instead of calling @code{printf()} directly, we define a macro
12426: that casts (converts) the Forth single-cell integer into a
12427: C @code{long long} before calling @code{printf()}.
12428: 
12429: doc-\c
12430: doc-c-function
12431: doc-c-value
12432: doc-c-variable
12433: 
12434: In order to work, this C interface invokes GCC at run-time and uses
12435: dynamic linking.  If these features are not available, there are
12436: other, less convenient and less portable C interfaces in @file{lib.fs}
12437: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
12438: mostly incompatible with each other and with the documented C
12439: interface; you can find some examples for the @file{lib.fs} interface
12440: in @file{lib.fs}.
12441: 
12442: 
12443: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
12444: @subsection Calling C function pointers from Forth
12445: @cindex C function pointers, calling from Forth
12446: 
12447: If you come across a C function pointer (e.g., in some C-constructed
12448: structure) and want to call it from your Forth program, you can also
12449: use the features explained until now to achieve that, as follows:
12450: 
12451: Let us assume that there is a C function pointer type @code{func1}
12452: defined in some header file @file{func1.h}, and you know that these
12453: functions take one integer argument and return an integer result; and
12454: you want to call functions through such pointers.  Just define
12455: 
12456: @example
12457: \c #include <func1.h>
12458: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12459: c-function call-func1 call_func1 n func -- n
12460: @end example
12461: 
12462: and then you can call a function pointed to by, say @code{func1a} as
12463: follows:
12464: 
12465: @example
12466: -5 func1a call-func1 .
12467: @end example
12468: 
12469: In the C part, @code{call_func} is defined as a macro to avoid having
12470: to declare the exact parameter and return types, so the C compiler
12471: knows them from the declaration of @code{func1}.
12472: 
12473: The Forth word @code{call-func1} is similar to @code{execute}, except
12474: that it takes a C @code{func1} pointer instead of a Forth execution
12475: token, and it is specific to @code{func1} pointers.  For each type of
12476: function pointer you want to call from Forth, you have to define
12477: a separate calling word.
12478: 
12479: 
12480: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12481: @subsection Defining library interfaces
12482: @cindex giving a name to a library interface
12483: @cindex library interface names
12484: 
12485: You can give a name to a bunch of C function declarations (a library
12486: interface), as follows:
12487: 
12488: @example
12489: c-library lseek-lib
12490: \c #define _FILE_OFFSET_BITS 64
12491: ...
12492: end-c-library
12493: @end example
12494: 
12495: The effect of giving such a name to the interface is that the names of
12496: the generated files will contain that name, and when you use the
12497: interface a second time, it will use the existing files instead of
12498: generating and compiling them again, saving you time.  Note that even
12499: if you change the declarations, the old (stale) files will be used,
12500: probably leading to errors.  So, during development of the
12501: declarations we recommend not using @code{c-library}.  Normally these
12502: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12503: that directory you can get rid of stale files.
12504: 
12505: Note that you should use @code{c-library} before everything else
12506: having anything to do with that library, as it resets some setup
12507: stuff.  The idea is that the typical use is to put each
12508: @code{c-library}...@code{end-library} unit in its own file, and to be
12509: able to include these files in any order.
12510: 
12511: Note that the library name is not allocated in the dictionary and
12512: therefore does not shadow dictionary names.  It is used in the file
12513: system, so you have to use naming conventions appropriate for file
12514: systems.  Also, you must not call a function you declare after
12515: @code{c-library} before you perform @code{end-c-library}.
12516: 
12517: A major benefit of these named library interfaces is that, once they
12518: are generated, the tools used to generated them (in particular, the C
12519: compiler and libtool) are no longer needed, so the interface can be
12520: used even on machines that do not have the tools installed.
12521: 
12522: doc-c-library-name
12523: doc-c-library
12524: doc-end-c-library
12525: 
12526: 
12527: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12528: @subsection Declaring OS-level libraries
12529: @cindex Shared libraries in C interface
12530: @cindex Dynamically linked libraries in C interface
12531: @cindex Libraries in C interface
12532: 
12533: For calling some C functions, you need to link with a specific
12534: OS-level library that contains that function.  E.g., the @code{sin}
12535: function requires linking a special library by using the command line
12536: switch @code{-lm}.  In our C iterface you do the equivalent thing by
12537: calling @code{add-lib} as follows:
12538: 
12539: @example
12540: clear-libs
12541: s" m" add-lib
12542: \c #include <math.h>
12543: c-function sin sin r -- r
12544: @end example
12545: 
12546: First, you clear any libraries that may have been declared earlier
12547: (you don't need them for @code{sin}); then you add the @code{m}
12548: library (actually @code{libm.so} or somesuch) to the currently
12549: declared libraries; you can add as many as you need.  Finally you
12550: declare the function as shown above.  Typically you will use the same
12551: set of library declarations for many function declarations; you need
12552: to write only one set for that, right at the beginning.
12553: 
12554: Note that you must not call @code{clear-libs} inside
12555: @code{c-library...end-c-library}; however, @code{c-library} performs
12556: the function of @code{clear-libs}, so @code{clear-libs} is not
12557: necessary, and you usually want to put @code{add-lib} calls inside
12558: @code{c-library...end-c-library}.
12559: 
12560: doc-clear-libs
12561: doc-add-lib
12562: 
12563: 
12564: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
12565: @subsection Callbacks
12566: @cindex Callback functions written in Forth
12567: @cindex C function pointers to Forth words
12568: 
12569: Callbacks are not yet supported by the documented C interface.  You
12570: can use the undocumented @file{lib.fs} interface for callbacks.
12571: 
12572: In some cases you have to pass a function pointer to a C function,
12573: i.e., the library wants to call back to your application (and the
12574: pointed-to function is called a callback function).  You can pass the
12575: address of an existing C function (that you get with @code{lib-sym},
12576: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12577: function, you probably want to define the function as a Forth word.
12578: 
12579: @c I don't understand the existing callback interface from the example - anton
12580: 
12581: 
12582: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12583: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12584: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12585: @c > > C-Funktionsadresse auf dem TOS).
12586: @c >
12587: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12588: @c > gesehen habe, wozu das gut ist.
12589: @c 
12590: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
12591: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
12592: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
12593: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
12594: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
12595: @c demselben Prototyp.
12596: 
12597: 
12598: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
12599: @subsection How the C interface works
12600: 
12601: The documented C interface works by generating a C code out of the
12602: declarations.
12603: 
12604: In particular, for every Forth word declared with @code{c-function},
12605: it generates a wrapper function in C that takes the Forth data from
12606: the Forth stacks, and calls the target C function with these data as
12607: arguments.  The C compiler then performs an implicit conversion
12608: between the Forth type from the stack, and the C type for the
12609: parameter, which is given by the C function prototype.  After the C
12610: function returns, the return value is likewise implicitly converted to
12611: a Forth type and written back on the stack.
12612: 
12613: The @code{\c} lines are literally included in the C code (but without
12614: the @code{\c}), and provide the necessary declarations so that the C
12615: compiler knows the C types and has enough information to perform the
12616: conversion.
12617: 
12618: These wrapper functions are eventually compiled and dynamically linked
12619: into Gforth, and then they can be called.
12620: 
12621: The libraries added with @code{add-lib} are used in the compile
12622: command line to specify dependent libraries with @code{-l@var{lib}},
12623: causing these libraries to be dynamically linked when the wrapper
12624: function is linked.
12625: 
12626: 
12627: @node Low-Level C Interface Words,  , C interface internals, C Interface
12628: @subsection Low-Level C Interface Words
12629: 
12630: doc-open-lib
12631: doc-lib-sym
12632: doc-lib-error
12633: doc-call-c
12634: 
12635: @c -------------------------------------------------------------
12636: @node Assembler and Code Words, Threading Words, C Interface, Words
12637: @section Assembler and Code Words
12638: @cindex assembler
12639: @cindex code words
12640: 
12641: @menu
12642: * Assembler Definitions::       Definitions in assembly language
12643: * Common Assembler::            Assembler Syntax
12644: * Common Disassembler::         
12645: * 386 Assembler::               Deviations and special cases
12646: * AMD64 Assembler::             
12647: * Alpha Assembler::             Deviations and special cases
12648: * MIPS assembler::              Deviations and special cases
12649: * PowerPC assembler::           Deviations and special cases
12650: * ARM Assembler::               Deviations and special cases
12651: * Other assemblers::            How to write them
12652: @end menu
12653: 
12654: @node Assembler Definitions, Common Assembler, Assembler and Code Words, Assembler and Code Words
12655: @subsection Definitions in assembly language
12656: 
12657: Gforth provides ways to implement words in assembly language (using
12658: @code{abi-code}...@code{end-code}), and also ways to define defining
12659: words with arbitrary run-time behaviour (like @code{does>}), where
12660: (unlike @code{does>}) the behaviour is not defined in Forth, but in
12661: assembly language (with @code{;code}).
12662: 
12663: However, the machine-independent nature of Gforth poses a few
12664: problems: First of all, Gforth runs on several architectures, so it
12665: can provide no standard assembler. It does provide assemblers for
12666: several of the architectures it runs on, though.  Moreover, you can
12667: use a system-independent assembler in Gforth, or compile machine code
12668: directly with @code{,} and @code{c,}.
12669: 
12670: Another problem is that the virtual machine registers of Gforth (the
12671: stack pointers and the virtual machine instruction pointer) depend on
12672: the installation and engine.  Also, which registers are free to use
12673: also depend on the installation and engine.  So any code written to
12674: run in the context of the Gforth virtual machine is essentially
12675: limited to the installation and engine it was developed for (it may
12676: run elsewhere, but you cannot rely on that).
12677: 
12678: Fortunately, you can define @code{abi-code} words in Gforth that are
12679: portable to any Gforth running on a platform with the same calling
12680: convention (ABI); typically this means portability to the same
12681: architecture/OS combination, sometimes crossing OS boundaries).
12682: 
12683: doc-assembler
12684: doc-init-asm
12685: doc-abi-code
12686: doc-end-code
12687: doc-code
12688: doc-;code
12689: doc-flush-icache
12690: 
12691: 
12692: If @code{flush-icache} does not work correctly, @code{abi-code} words
12693: etc. will not work (reliably), either.
12694: 
12695: The typical usage of these words can be shown most easily by analogy
12696: to the equivalent high-level defining words:
12697: 
12698: @example
12699: : foo                              abi-code foo
12700:    <high-level Forth words>              <assembler>
12701: ;                                  end-code
12702:                                 
12703: : bar                              : bar
12704:    <high-level Forth words>           <high-level Forth words>
12705:    CREATE                             CREATE
12706:       <high-level Forth words>           <high-level Forth words>
12707:    DOES>                              ;code
12708:       <high-level Forth words>           <assembler>
12709: ;                                  end-code
12710: @end example
12711: 
12712: For using @code{abi-code}, take a look at the ABI documentation of
12713: your platform to see how the parameters are passed (so you know where
12714: you get the stack pointers) and how the return value is passed (so you
12715: know where the data stack pointer is returned).  The ABI documentation
12716: also tells you which registers are saved by the caller (caller-saved),
12717: so you are free to destroy them in your code, and which registers have
12718: to be preserved by the called word (callee-saved), so you have to save
12719: them before using them, and restore them afterwards.  For some
12720: architectures and OSs we give short summaries of the parts of the
12721: calling convention in the appropriate sections.  More
12722: reverse-engineering oriented people can also find out about the
12723: passing and returning of the stack pointers through @code{see
12724: abi-call}.
12725: 
12726: Most ABIs pass the parameters through registers, but some (in
12727: particular the most common 386 (aka IA-32) calling conventions) pass
12728: them on the architectural stack.  The common ABIs all pass the return
12729: value in a register.
12730: 
12731: Other things you need to know for using @code{abi-code} is that both
12732: the data and the FP stack grow downwards (towards lower addresses) in
12733: Gforth, with @code{1 cells} size per cell, and @code{1 floats} size
12734: per FP value.
12735: 
12736: Here's an example of using @code{abi-code} on the 386 architecture:
12737: 
12738: @example
12739: abi-code my+ ( n1 n2 -- n )
12740: 4 sp d) ax mov \ sp into return reg
12741: ax )    cx mov \ tos
12742: 4 #     ax add \ update sp (pop)
12743: cx    ax ) add \ sec = sec+tos
12744: ret            \ return from my+
12745: end-code
12746: @end example
12747: 
12748: An AMD64 variant of this example can be found in @ref{AMD64 Assembler}.
12749: 
12750: Here's a 386 example that deals with FP values:
12751: 
12752: @example
12753: abi-code my-f+ ( r1 r2 -- r )
12754: 8 sp d) cx mov  \ load address of fp
12755: cx )    dx mov  \ load fp
12756: .fl dx )   fld  \ r2
12757: 8 #     dx add  \ update fp
12758: .fl dx )   fadd \ r1+r2
12759: .fl dx )   fstp \ store r
12760: dx    cx ) mov  \ store new fp
12761: 4 sp d) ax mov  \ sp into return reg
12762: ret             \ return from my-f+
12763: end-code
12764: @end example
12765: 
12766: 
12767: @node Common Assembler, Common Disassembler, Assembler Definitions, Assembler and Code Words
12768: @subsection Common Assembler
12769: 
12770: The assemblers in Gforth generally use a postfix syntax, i.e., the
12771: instruction name follows the operands.
12772: 
12773: The operands are passed in the usual order (the same that is used in the
12774: manual of the architecture).  Since they all are Forth words, they have
12775: to be separated by spaces; you can also use Forth words to compute the
12776: operands.
12777: 
12778: The instruction names usually end with a @code{,}.  This makes it easier
12779: to visually separate instructions if you put several of them on one
12780: line; it also avoids shadowing other Forth words (e.g., @code{and}).
12781: 
12782: Registers are usually specified by number; e.g., (decimal) @code{11}
12783: specifies registers R11 and F11 on the Alpha architecture (which one,
12784: depends on the instruction).  The usual names are also available, e.g.,
12785: @code{s2} for R11 on Alpha.
12786: 
12787: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12788: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12789: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12790: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
12791: conditions are specified in a way specific to each assembler.
12792: 
12793: The rest of this section is of interest mainly for those who want to
12794: define @code{code} words (instead of the more portable @code{abi-code}
12795: words).
12796: 
12797: Note that the register assignments of the Gforth engine can change
12798: between Gforth versions, or even between different compilations of the
12799: same Gforth version (e.g., if you use a different GCC version).  If
12800: you are using @code{CODE} instead of @code{ABI-CODE}, and you want to
12801: refer to Gforth's registers (e.g., the stack pointer or TOS), I
12802: recommend defining your own words for refering to these registers, and
12803: using them later on; then you can adapt to a changed register
12804: assignment.
12805: 
12806: The most common use of these registers is to end a @code{code}
12807: definition with a dispatch to the next word (the @code{next} routine).
12808: A portable way to do this is to jump to @code{' noop >code-address}
12809: (of course, this is less efficient than integrating the @code{next}
12810: code and scheduling it well).  When using @code{ABI-CODE}, you can
12811: just assemble a normal subroutine return (but make sure you return the
12812: data stack pointer).
12813: 
12814: Another difference between Gforth versions is that the top of stack is
12815: kept in memory in @code{gforth} and, on most platforms, in a register
12816: in @code{gforth-fast}.  For @code{ABI-CODE} definitions, any stack
12817: caching registers are guaranteed to be flushed to the stack, allowing
12818: you to reliably access the top of stack in memory.
12819: 
12820: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12821: @subsection Common Disassembler
12822: @cindex disassembler, general
12823: @cindex gdb disassembler
12824: 
12825: You can disassemble a @code{code} word with @code{see}
12826: (@pxref{Debugging}).  You can disassemble a section of memory with
12827: 
12828: doc-discode
12829: 
12830: There are two kinds of disassembler for Gforth: The Forth disassembler
12831: (available on some CPUs) and the gdb disassembler (available on
12832: platforms with @command{gdb} and @command{mktemp}).  If both are
12833: available, the Forth disassembler is used by default.  If you prefer
12834: the gdb disassembler, say
12835: 
12836: @example
12837: ' disasm-gdb is discode
12838: @end example
12839: 
12840: If neither is available, @code{discode} performs @code{dump}.
12841: 
12842: The Forth disassembler generally produces output that can be fed into the
12843: assembler (i.e., same syntax, etc.).  It also includes additional
12844: information in comments.  In particular, the address of the instruction
12845: is given in a comment before the instruction.
12846: 
12847: The gdb disassembler produces output in the same format as the gdb
12848: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12849: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12850: the 386 and AMD64 architectures).
12851: 
12852: @code{See} may display more or less than the actual code of the word,
12853: because the recognition of the end of the code is unreliable.  You can
12854: use @code{discode} if it did not display enough.  It may display more, if
12855: the code word is not immediately followed by a named word.  If you have
12856: something else there, you can follow the word with @code{align latest ,}
12857: to ensure that the end is recognized.
12858: 
12859: @node 386 Assembler, AMD64 Assembler, Common Disassembler, Assembler and Code Words
12860: @subsection 386 Assembler
12861: 
12862: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12863: available under GPL, and originally part of bigFORTH.
12864: 
12865: The 386 disassembler included in Gforth was written by Andrew McKewan
12866: and is in the public domain.
12867: 
12868: The disassembler displays code in an Intel-like prefix syntax.
12869: 
12870: The assembler uses a postfix syntax with AT&T-style parameter order
12871: (i.e., destination last).
12872: 
12873: The assembler includes all instruction of the Athlon, i.e. 486 core
12874: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12875: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12876: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
12877: 
12878: There are several prefixes to switch between different operation sizes,
12879: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12880: double-word accesses. Addressing modes can be switched with @code{.wa}
12881: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12882: need a prefix for byte register names (@code{AL} et al).
12883: 
12884: For floating point operations, the prefixes are @code{.fs} (IEEE
12885: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12886: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).  The
12887: default is @code{.fx}, so you need to specify @code{.fl} explicitly
12888: when dealing with Gforth FP values.
12889: 
12890: The MMX opcodes don't have size prefixes, they are spelled out like in
12891: the Intel assembler. Instead of move from and to memory, there are
12892: PLDQ/PLDD and PSTQ/PSTD.
12893: 
12894: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12895: ax.  Immediate values are indicated by postfixing them with @code{#},
12896: e.g., @code{3 #}.  Here are some examples of addressing modes in various
12897: syntaxes:
12898: 
12899: @example
12900: Gforth          Intel (NASM)   AT&T (gas)      Name
12901: .w ax           ax             %ax             register (16 bit)
12902: ax              eax            %eax            register (32 bit)
12903: 3 #             offset 3       $3              immediate
12904: 1000 #)         byte ptr 1000  1000            displacement
12905: bx )            [ebx]          (%ebx)          base
12906: 100 di d)       100[edi]       100(%edi)       base+displacement
12907: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
12908: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
12909: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
12910: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12911: @end example
12912: 
12913: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12914: @code{DI)} to enforce 32-bit displacement fields (useful for
12915: later patching).
12916: 
12917: Some example of instructions are:
12918: 
12919: @example
12920: ax bx mov             \ move ebx,eax
12921: 3 # ax mov            \ mov eax,3
12922: 100 di d) ax mov      \ mov eax,100[edi]
12923: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
12924: .w ax bx mov          \ mov bx,ax
12925: @end example
12926: 
12927: The following forms are supported for binary instructions:
12928: 
12929: @example
12930: <reg> <reg> <inst>
12931: <n> # <reg> <inst>
12932: <mem> <reg> <inst>
12933: <reg> <mem> <inst>
12934: <n> # <mem> <inst>
12935: @end example
12936: 
12937: The shift/rotate syntax is:
12938: 
12939: @example
12940: <reg/mem> 1 # shl \ shortens to shift without immediate
12941: <reg/mem> 4 # shl
12942: <reg/mem> cl shl
12943: @end example
12944: 
12945: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12946: the byte version.
12947: 
12948: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12949: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12950: pc < >= <= >}. (Note that most of these words shadow some Forth words
12951: when @code{assembler} is in front of @code{forth} in the search path,
12952: e.g., in @code{code} words).  Currently the control structure words use
12953: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12954: to shuffle them (you can also use @code{swap} etc.).
12955: 
12956: Based on the Intel ABI (used in Linux), @code{abi-code} words can find
12957: the data stack pointer at @code{4 sp d)}, and the address of the FP
12958: stack pointer at @code{8 sp d)}; the data stack pointer is returned in
12959: @code{ax}; @code{Ax}, @code{cx}, and @code{dx} are caller-saved, so
12960: you do not need to preserve their values inside the word.  You can
12961: return from the word with @code{ret}, the parameters are cleaned up by
12962: the caller.
12963: 
12964: For examples of 386 @code{abi-code} words, see @ref{Assembler Definitions}.
12965: 
12966: 
12967: @node AMD64 Assembler, Alpha Assembler, 386 Assembler, Assembler and Code Words
12968: @subsection AMD64 (x86_64) Assembler
12969: 
12970: The AMD64 assembler is a slightly modified version of the 386
12971: assembler, and as such shares most of the syntax.  Two new prefixes,
12972: @code{.q} and @code{.qa}, are provided to select 64-bit operand and
12973: address sizes respectively.  64-bit sizes are the default, so normally
12974: you only have to use the other prefixes.  Also there are additional
12975: register operands @code{R8}-@code{R15}.
12976: 
12977: The registers lack the 'e' or 'r' prefix; even in 64 bit mode,
12978: @code{rax} is called @code{ax}.  Additional register operands are
12979: available to refer to the lowest-significant byte of all registers:
12980: @code{R8L}-@code{R15L}, @code{SPL}, @code{BPL}, @code{SIL},
12981: @code{DIL}.
12982: 
12983: The Linux-AMD64 calling convention is to pass the first 6 integer
12984: parameters in rdi, rsi, rdx, rcx, r8 and r9 and to return the result
12985: in rax and rdx; to pass the first 8 FP parameters in xmm0--xmm7 and to
12986: return FP results in xmm0--xmm1.  So @code{abi-code} words get the
12987: data stack pointer in @code{di} and the address of the FP stack
12988: pointer in @code{si}, and return the data stack pointer in @code{ax}.
12989: The other caller-saved registers are: r10, r11, xmm8-xmm15.  This
12990: calling convention reportedly is also used in other non-Microsoft OSs.
12991: @c source: http://en.wikipedia.org/wiki/X86_calling_conventions#AMD64_ABI_convention
12992: 
12993: @c source: http://msdn.microsoft.com/en-us/library/9b372w95(v=VS.90).aspx
12994: Windows x64 passes the first four integer parameters in rcx, rdx, r8
12995: and r9 and return the integer result in rax.  The other caller-saved
12996: registers are r10 and r11.
12997: 
12998: Here is an example of an AMD64 @code{abi-code} word:
12999: 
13000: @example
13001: abi-code my+  ( n1 n2 -- n3 )
13002: \ SP passed in di, returned in ax,  address of FP passed in si
13003: 8 di d) ax lea        \ compute new sp in result reg
13004: di )    dx mov        \ get old tos
13005: dx    ax ) add        \ add to new tos
13006: ret
13007: end-code
13008: @end example
13009: 
13010: Here's a AMD64 example that deals with FP values:
13011: 
13012: @example
13013: abi-code my-f+  ( r1 r2 -- r )
13014: \ SP passed in di, returned in ax,  address of FP passed in si
13015: si )       dx mov         \ load fp
13016: 8 dx d)  xmm0 movsd       \ r2
13017: dx )     xmm0 addsd       \ r1+r2
13018: xmm0  8 dx d) movsd       \ store r
13019: 8 #      si ) add         \ update fp
13020: di         ax mov         \ sp into return reg
13021: ret
13022: end-code
13023: @end example
13024: 
13025: @node Alpha Assembler, MIPS assembler, AMD64 Assembler, Assembler and Code Words
13026: @subsection Alpha Assembler
13027: 
13028: The Alpha assembler and disassembler were originally written by Bernd
13029: Thallner.
13030: 
13031: The register names @code{a0}--@code{a5} are not available to avoid
13032: shadowing hex numbers.
13033: 
13034: Immediate forms of arithmetic instructions are distinguished by a
13035: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
13036: does not count as arithmetic instruction).
13037: 
13038: You have to specify all operands to an instruction, even those that
13039: other assemblers consider optional, e.g., the destination register for
13040: @code{br,}, or the destination register and hint for @code{jmp,}.
13041: 
13042: You can specify conditions for @code{if,} by removing the first @code{b}
13043: and the trailing @code{,} from a branch with a corresponding name; e.g.,
13044: 
13045: @example
13046: 11 fgt if, \ if F11>0e
13047:   ...
13048: endif,
13049: @end example
13050: 
13051: @code{fbgt,} gives @code{fgt}.  
13052: 
13053: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
13054: @subsection MIPS assembler
13055: 
13056: The MIPS assembler was originally written by Christian Pirker.
13057: 
13058: Currently the assembler and disassembler covers most of the MIPS32
13059: architecture and doesn't support FP instructions.
13060: 
13061: The register names @code{$a0}--@code{$a3} are not available to avoid
13062: shadowing hex numbers.  Use register numbers @code{$4}--@code{$7}
13063: instead.
13064: 
13065: Nothing distinguishes registers from immediate values.  Use explicit
13066: opcode names with the @code{i} suffix for instructions with immediate
13067: argument.  E.g. @code{addiu,} in place of @code{addu,}.
13068: 
13069: Where the architecture manual specifies several formats for the
13070: instruction (e.g., for @code{jalr,}),use the one with more arguments
13071: (i.e. two for @code{jalr,}).  When in doubt, see
13072: @code{arch/mips/testasm.fs} for an example of correct use.
13073: 
13074: Branches and jumps in the MIPS architecture have a delay slot.  You
13075: have to fill it manually (the simplest way is to use @code{nop,}), the
13076: assembler does not do it for you (unlike @command{as}).  Even
13077: @code{if,}, @code{ahead,}, @code{until,}, @code{again,},
13078: @code{while,}, @code{else,} and @code{repeat,} need a delay slot.
13079: Since @code{begin,} and @code{then,} just specify branch targets, they
13080: are not affected.  For branches the argument specifying the target is
13081: a relative address.  Add the address of the delay slot to get the
13082: absolute address.
13083: 
13084: Note that you must not put branches nor jumps (nor control-flow
13085: instructions) into the delay slot.  Also it is a bad idea to put
13086: pseudo-ops such as @code{li,} into a delay slot, as these may expand
13087: to several instructions.  The MIPS I architecture also had load delay
13088: slots, and newer MIPSes still have restrictions on using @code{mfhi,}
13089: and @code{mflo,}.  Be careful to satisfy these restrictions, the
13090: assembler does not do it for you.
13091: 
13092: Some example of instructions are:
13093: 
13094: @example
13095: $ra  12 $sp  sw,         \ sw    ra,12(sp)
13096: $4    8 $s0  lw,         \ lw    a0,8(s0)
13097: $v0  $0  lui,            \ lui   v0,0x0
13098: $s0  $s4  $12  addiu,    \ addiu s0,s4,0x12
13099: $s0  $s4  $4  addu,      \ addu  s0,s4,$a0
13100: $ra  $t9  jalr,          \ jalr  t9
13101: @end example
13102: 
13103: You can specify the conditions for @code{if,} etc. by taking a
13104: conditional branch and leaving away the @code{b} at the start and the
13105: @code{,} at the end.  E.g.,
13106: 
13107: @example
13108: 4 5 eq if,
13109:   ... \ do something if $4 equals $5
13110: then,
13111: @end example
13112: 
13113: The calling conventions for 32-bit MIPS machines is to pass the first
13114: 4 arguments in registers @code{$4}..@code{$7}, and to use
13115: @code{$v0}-@code{$v1} for return values.  In addition to these
13116: registers, it is ok to clobber registers @code{$t0}-@code{$t8} without
13117: saving and restoring them.
13118: 
13119: If you use @code{jalr,} to call into dynamic library routines, you
13120: must first load the called function's address into @code{$t9}, which
13121: is used by position-indirect code to do relative memory accesses.
13122: 
13123: Here is an example of a MIPS32 @code{abi-code} word:
13124: 
13125: @example
13126: abi-code my+  ( n1 n2 -- n3 )
13127:   \ SP passed in $4, returned in $v0
13128:   $t0  4 $4  lw,         \ load n1, n2 from stack
13129:   $t1  0 $4  lw,    
13130:   $t0  $t0  $t1  addu,   \ add n1+n2, result in $t0
13131:   $t0  4 $4  sw,         \ store result (overwriting n1)
13132:   $ra  jr,               \ return to caller
13133:   $v0  $4  4  addiu,     \ (delay slot) return uptated SP in $v0
13134: end-code
13135: @end example
13136: 
13137: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
13138: @subsection PowerPC assembler
13139: 
13140: The PowerPC assembler and disassembler were contributed by Michal
13141: Revucky.
13142: 
13143: This assembler does not follow the convention of ending mnemonic names
13144: with a ``,'', so some mnemonic names shadow regular Forth words (in
13145: particular: @code{and or xor fabs}); so if you want to use the Forth
13146: words, you have to make them visible first, e.g., with @code{also
13147: forth}.
13148: 
13149: Registers are referred to by their number, e.g., @code{9} means the
13150: integer register 9 or the FP register 9 (depending on the
13151: instruction).
13152: 
13153: Because there is no way to distinguish registers from immediate values,
13154: you have to explicitly use the immediate forms of instructions, i.e.,
13155: @code{addi,}, not just @code{add,}.
13156: 
13157: The assembler and disassembler usually support the most general form
13158: of an instruction, but usually not the shorter forms (especially for
13159: branches).
13160: 
13161: 
13162: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
13163: @subsection ARM Assembler
13164: 
13165: The ARM assembler includes all instruction of ARM architecture version
13166: 4, and the BLX instruction from architecture 5.  It does not (yet)
13167: have support for Thumb instructions.  It also lacks support for any
13168: co-processors.
13169: 
13170: The assembler uses a postfix syntax with the same operand order as
13171: used in the ARM Architecture Reference Manual.  Mnemonics are suffixed
13172: by a comma.
13173: 
13174: Registers are specified by their names @code{r0} through @code{r15},
13175: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
13176: @code{fp} provided for convenience.  Note that @code{ip} refers to
13177: the``intra procedure call scratch register'' (@code{r12}) and does not
13178: refer to an instruction pointer.  @code{sp} refers to the ARM ABI
13179: stack pointer (@code{r13}) and not the Forth stack pointer.
13180: 
13181: Condition codes can be specified anywhere in the instruction, but will
13182: be most readable if specified just in front of the mnemonic.  The 'S'
13183: flag is not a separate word, but encoded into instruction mnemonics,
13184: ie. just use @code{adds,} instead of @code{add,} if you want the
13185: status register to be updated.
13186: 
13187: The following table lists the syntax of operands for general
13188: instructions:
13189: 
13190: @example
13191: Gforth          normal assembler      description
13192: 123 #           #123                  immediate
13193: r12             r12                   register
13194: r12 4 #LSL      r12, LSL #4           shift left by immediate
13195: r12 r1 #LSL     r12, LSL r1           shift left by register
13196: r12 4 #LSR      r12, LSR #4           shift right by immediate
13197: r12 r1 #LSR     r12, LSR r1           shift right by register
13198: r12 4 #ASR      r12, ASR #4           arithmetic shift right
13199: r12 r1 #ASR     r12, ASR r1           ... by register
13200: r12 4 #ROR      r12, ROR #4           rotate right by immediate
13201: r12 r1 #ROR     r12, ROR r1           ... by register
13202: r12 RRX         r12, RRX              rotate right with extend by 1
13203: @end example
13204: 
13205: Memory operand syntax is listed in this table:
13206: 
13207: @example
13208: Gforth            normal assembler      description
13209: r4 ]              [r4]                  register
13210: r4 4 #]           [r4, #+4]             register with immediate offset
13211: r4 -4 #]          [r4, #-4]             with negative offset
13212: r4 r1 +]          [r4, +r1]             register with register offset
13213: r4 r1 -]          [r4, -r1]             with negated register offset
13214: r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
13215: r4 4 #]!          [r4, #+4]!            immediate preincrement
13216: r4 r1 +]!         [r4, +r1]!            register preincrement
13217: r4 r1 -]!         [r4, +r1]!            register predecrement
13218: r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
13219: r4 -4 ]#          [r4], #-4             immediate postdecrement
13220: r4 r1 ]+          [r4], r1              register postincrement
13221: r4 r1 ]-          [r4], -r1             register postdecrement
13222: r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
13223: ' xyz >body [#]   xyz                   PC-relative addressing
13224: @end example
13225: 
13226: Register lists for load/store multiple instructions are started and
13227: terminated by using the words @code{@{} and @code{@}} respectively.
13228: Between braces, register names can be listed one by one or register
13229: ranges can be formed by using the postfix operator @code{r-r}.  The
13230: @code{^} flag is not encoded in the register list operand, but instead
13231: directly encoded into the instruction mnemonic, ie. use @code{^ldm,}
13232: and @code{^stm,}.
13233: 
13234: Addressing modes for load/store multiple are not encoded as
13235: instruction suffixes, but instead specified like an addressing mode,
13236: Use one of @code{DA}, @code{IA}, @code{DB}, @code{IB}, @code{DA!},
13237: @code{IA!}, @code{DB!} or @code{IB!}.
13238: 
13239: The following table gives some examples:
13240: 
13241: @example
13242: Gforth                           normal assembler
13243: r4 ia  @{ r0 r7 r8 @}  stm,        stmia    r4, @{r0,r7,r8@}
13244: r4 db!  @{ r0 r7 r8 @}  ldm,       ldmdb    r4!, @{r0,r7,r8@}
13245: sp ia!  @{ r0 r15 r-r @}  ^ldm,    ldmfd    sp!, @{r0-r15@}^
13246: @end example
13247: 
13248: Control structure words typical for Forth assemblers are available:
13249: @code{if,} @code{ahead,} @code{then,} @code{else,} @code{begin,}
13250: @code{until,} @code{again,} @code{while,} @code{repeat,}
13251: @code{repeat-until,}.  Conditions are specified in front of these words:
13252: 
13253: @example
13254: r1 r2 cmp,    \ compare r1 and r2
13255: eq if,        \ equal?
13256:    ...          \ code executed if r1 == r2
13257: then,
13258: @end example
13259: 
13260: Example of a definition using the ARM assembler:
13261: 
13262: @example
13263: abi-code my+ ( n1 n2 --  n3 )
13264:    \ arm abi: r0=SP, r1=&FP, r2,r3,r12 saved by caller
13265:    r0 IA!  @{ r2 r3 @}  ldm,     \ pop r2 = n2, r3 = n1
13266:    r3  r2  r3         add,     \ r3 = n1+n1
13267:    r3  r0 -4 #]!      str,     \ push r3
13268:    pc  lr             mov,     \ return to caller, new SP in r0
13269: end-code
13270: @end example
13271: 
13272: @node Other assemblers,  , ARM Assembler, Assembler and Code Words
13273: @subsection Other assemblers
13274: 
13275: If you want to contribute another assembler/disassembler, please contact
13276: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
13277: an assembler already.  If you are writing them from scratch, please use
13278: a similar syntax style as the one we use (i.e., postfix, commas at the
13279: end of the instruction names, @pxref{Common Assembler}); make the output
13280: of the disassembler be valid input for the assembler, and keep the style
13281: similar to the style we used.
13282: 
13283: Hints on implementation: The most important part is to have a good test
13284: suite that contains all instructions.  Once you have that, the rest is
13285: easy.  For actual coding you can take a look at
13286: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
13287: the assembler and disassembler, avoiding redundancy and some potential
13288: bugs.  You can also look at that file (and @pxref{Advanced does> usage
13289: example}) to get ideas how to factor a disassembler.
13290: 
13291: Start with the disassembler, because it's easier to reuse data from the
13292: disassembler for the assembler than the other way round.
13293: 
13294: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13295: how simple it can be.
13296: 
13297: 
13298: 
13299: 
13300: @c -------------------------------------------------------------
13301: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13302: @section Threading Words
13303: @cindex threading words
13304: 
13305: @cindex code address
13306: These words provide access to code addresses and other threading stuff
13307: in Gforth (and, possibly, other interpretive Forths). It more or less
13308: abstracts away the differences between direct and indirect threading
13309: (and, for direct threading, the machine dependences). However, at
13310: present this wordset is still incomplete. It is also pretty low-level;
13311: some day it will hopefully be made unnecessary by an internals wordset
13312: that abstracts implementation details away completely.
13313: 
13314: The terminology used here stems from indirect threaded Forth systems; in
13315: such a system, the XT of a word is represented by the CFA (code field
13316: address) of a word; the CFA points to a cell that contains the code
13317: address.  The code address is the address of some machine code that
13318: performs the run-time action of invoking the word (e.g., the
13319: @code{dovar:} routine pushes the address of the body of the word (a
13320: variable) on the stack
13321: ).
13322: 
13323: @cindex code address
13324: @cindex code field address
13325: In an indirect threaded Forth, you can get the code address of @i{name}
13326: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13327: >code-address}, independent of the threading method.
13328: 
13329: doc-threading-method
13330: doc->code-address
13331: doc-code-address!
13332: 
13333: @cindex @code{does>}-handler
13334: @cindex @code{does>}-code
13335: For a word defined with @code{DOES>}, the code address usually points to
13336: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13337: routine (in Gforth on some platforms, it can also point to the dodoes
13338: routine itself).  What you are typically interested in, though, is
13339: whether a word is a @code{DOES>}-defined word, and what Forth code it
13340: executes; @code{>does-code} tells you that.
13341: 
13342: doc->does-code
13343: 
13344: To create a @code{DOES>}-defined word with the following basic words,
13345: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13346: @code{/does-handler} aus behind you have to place your executable Forth
13347: code.  Finally you have to create a word and modify its behaviour with
13348: @code{does-handler!}.
13349: 
13350: doc-does-code!
13351: doc-does-handler!
13352: doc-/does-handler
13353: 
13354: The code addresses produced by various defining words are produced by
13355: the following words:
13356: 
13357: doc-docol:
13358: doc-docon:
13359: doc-dovar:
13360: doc-douser:
13361: doc-dodefer:
13362: doc-dofield:
13363: 
13364: @cindex definer
13365: The following two words generalize @code{>code-address},
13366: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13367: 
13368: doc->definer
13369: doc-definer!
13370: 
13371: @c -------------------------------------------------------------
13372: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
13373: @section Passing Commands to the Operating System
13374: @cindex operating system - passing commands
13375: @cindex shell commands
13376: 
13377: Gforth allows you to pass an arbitrary string to the host operating
13378: system shell (if such a thing exists) for execution.
13379: 
13380: doc-sh
13381: doc-system
13382: doc-$?
13383: doc-getenv
13384: 
13385: @c -------------------------------------------------------------
13386: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13387: @section Keeping track of Time
13388: @cindex time-related words
13389: 
13390: doc-ms
13391: doc-time&date
13392: doc-utime
13393: doc-cputime
13394: 
13395: 
13396: @c -------------------------------------------------------------
13397: @node Miscellaneous Words,  , Keeping track of Time, Words
13398: @section Miscellaneous Words
13399: @cindex miscellaneous words
13400: 
13401: @comment TODO find homes for these
13402: 
13403: These section lists the ANS Forth words that are not documented
13404: elsewhere in this manual. Ultimately, they all need proper homes.
13405: 
13406: doc-quit
13407: 
13408: The following ANS Forth words are not currently supported by Gforth 
13409: (@pxref{ANS conformance}):
13410: 
13411: @code{EDITOR} 
13412: @code{EMIT?} 
13413: @code{FORGET} 
13414: 
13415: @c ******************************************************************
13416: @node Error messages, Tools, Words, Top
13417: @chapter Error messages
13418: @cindex error messages
13419: @cindex backtrace
13420: 
13421: A typical Gforth error message looks like this:
13422: 
13423: @example
13424: in file included from \evaluated string/:-1
13425: in file included from ./yyy.fs:1
13426: ./xxx.fs:4: Invalid memory address
13427: >>>bar<<<
13428: Backtrace:
13429: $400E664C @@
13430: $400E6664 foo
13431: @end example
13432: 
13433: The message identifying the error is @code{Invalid memory address}.  The
13434: error happened when text-interpreting line 4 of the file
13435: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13436: word on the line where the error happened, is pointed out (with
13437: @code{>>>} and @code{<<<}).
13438: 
13439: The file containing the error was included in line 1 of @file{./yyy.fs},
13440: and @file{yyy.fs} was included from a non-file (in this case, by giving
13441: @file{yyy.fs} as command-line parameter to Gforth).
13442: 
13443: At the end of the error message you find a return stack dump that can be
13444: interpreted as a backtrace (possibly empty). On top you find the top of
13445: the return stack when the @code{throw} happened, and at the bottom you
13446: find the return stack entry just above the return stack of the topmost
13447: text interpreter.
13448: 
13449: To the right of most return stack entries you see a guess for the word
13450: that pushed that return stack entry as its return address. This gives a
13451: backtrace. In our case we see that @code{bar} called @code{foo}, and
13452: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13453: address} exception).
13454: 
13455: Note that the backtrace is not perfect: We don't know which return stack
13456: entries are return addresses (so we may get false positives); and in
13457: some cases (e.g., for @code{abort"}) we cannot determine from the return
13458: address the word that pushed the return address, so for some return
13459: addresses you see no names in the return stack dump.
13460: 
13461: @cindex @code{catch} and backtraces
13462: The return stack dump represents the return stack at the time when a
13463: specific @code{throw} was executed.  In programs that make use of
13464: @code{catch}, it is not necessarily clear which @code{throw} should be
13465: used for the return stack dump (e.g., consider one @code{throw} that
13466: indicates an error, which is caught, and during recovery another error
13467: happens; which @code{throw} should be used for the stack dump?).
13468: Gforth presents the return stack dump for the first @code{throw} after
13469: the last executed (not returned-to) @code{catch} or @code{nothrow};
13470: this works well in the usual case. To get the right backtrace, you
13471: usually want to insert @code{nothrow} or @code{['] false catch drop}
13472: after a @code{catch} if the error is not rethrown.
13473: 
13474: @cindex @code{gforth-fast} and backtraces
13475: @cindex @code{gforth-fast}, difference from @code{gforth}
13476: @cindex backtraces with @code{gforth-fast}
13477: @cindex return stack dump with @code{gforth-fast}
13478: @code{Gforth} is able to do a return stack dump for throws generated
13479: from primitives (e.g., invalid memory address, stack empty etc.);
13480: @code{gforth-fast} is only able to do a return stack dump from a
13481: directly called @code{throw} (including @code{abort} etc.).  Given an
13482: exception caused by a primitive in @code{gforth-fast}, you will
13483: typically see no return stack dump at all; however, if the exception is
13484: caught by @code{catch} (e.g., for restoring some state), and then
13485: @code{throw}n again, the return stack dump will be for the first such
13486: @code{throw}.
13487: 
13488: @c ******************************************************************
13489: @node Tools, ANS conformance, Error messages, Top
13490: @chapter Tools
13491: 
13492: @menu
13493: * ANS Report::                  Report the words used, sorted by wordset.
13494: * Stack depth changes::         Where does this stack item come from?
13495: @end menu
13496: 
13497: See also @ref{Emacs and Gforth}.
13498: 
13499: @node ANS Report, Stack depth changes, Tools, Tools
13500: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13501: @cindex @file{ans-report.fs}
13502: @cindex report the words used in your program
13503: @cindex words used in your program
13504: 
13505: If you want to label a Forth program as ANS Forth Program, you must
13506: document which wordsets the program uses; for extension wordsets, it is
13507: helpful to list the words the program requires from these wordsets
13508: (because Forth systems are allowed to provide only some words of them).
13509: 
13510: The @file{ans-report.fs} tool makes it easy for you to determine which
13511: words from which wordset and which non-ANS words your application
13512: uses. You simply have to include @file{ans-report.fs} before loading the
13513: program you want to check. After loading your program, you can get the
13514: report with @code{print-ans-report}. A typical use is to run this as
13515: batch job like this:
13516: @example
13517: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13518: @end example
13519: 
13520: The output looks like this (for @file{compat/control.fs}):
13521: @example
13522: The program uses the following words
13523: from CORE :
13524: : POSTPONE THEN ; immediate ?dup IF 0= 
13525: from BLOCK-EXT :
13526: \ 
13527: from FILE :
13528: ( 
13529: @end example
13530: 
13531: @subsection Caveats
13532: 
13533: Note that @file{ans-report.fs} just checks which words are used, not whether
13534: they are used in an ANS Forth conforming way!
13535: 
13536: Some words are defined in several wordsets in the
13537: standard. @file{ans-report.fs} reports them for only one of the
13538: wordsets, and not necessarily the one you expect. It depends on usage
13539: which wordset is the right one to specify. E.g., if you only use the
13540: compilation semantics of @code{S"}, it is a Core word; if you also use
13541: its interpretation semantics, it is a File word.
13542: 
13543: 
13544: @node Stack depth changes,  , ANS Report, Tools
13545: @section Stack depth changes during interpretation
13546: @cindex @file{depth-changes.fs}
13547: @cindex depth changes during interpretation
13548: @cindex stack depth changes during interpretation
13549: @cindex items on the stack after interpretation
13550: 
13551: Sometimes you notice that, after loading a file, there are items left
13552: on the stack.  The tool @file{depth-changes.fs} helps you find out
13553: quickly where in the file these stack items are coming from.
13554: 
13555: The simplest way of using @file{depth-changes.fs} is to include it
13556: before the file(s) you want to check, e.g.:
13557: 
13558: @example
13559: gforth depth-changes.fs my-file.fs
13560: @end example
13561: 
13562: This will compare the stack depths of the data and FP stack at every
13563: empty line (in interpretation state) against these depths at the last
13564: empty line (in interpretation state).  If the depths are not equal,
13565: the position in the file and the stack contents are printed with
13566: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
13567: change has occured in the paragraph of non-empty lines before the
13568: indicated line.  It is a good idea to leave an empty line at the end
13569: of the file, so the last paragraph is checked, too.
13570: 
13571: Checking only at empty lines usually works well, but sometimes you
13572: have big blocks of non-empty lines (e.g., when building a big table),
13573: and you want to know where in this block the stack depth changed.  You
13574: can check all interpreted lines with
13575: 
13576: @example
13577: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13578: @end example
13579: 
13580: This checks the stack depth at every end-of-line.  So the depth change
13581: occured in the line reported by the @code{~~} (not in the line
13582: before).
13583: 
13584: Note that, while this offers better accuracy in indicating where the
13585: stack depth changes, it will often report many intentional stack depth
13586: changes (e.g., when an interpreted computation stretches across
13587: several lines).  You can suppress the checking of some lines by
13588: putting backslashes at the end of these lines (not followed by white
13589: space), and using
13590: 
13591: @example
13592: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13593: @end example
13594: 
13595: @c ******************************************************************
13596: @node ANS conformance, Standard vs Extensions, Tools, Top
13597: @chapter ANS conformance
13598: @cindex ANS conformance of Gforth
13599: 
13600: To the best of our knowledge, Gforth is an
13601: 
13602: ANS Forth System
13603: @itemize @bullet
13604: @item providing the Core Extensions word set
13605: @item providing the Block word set
13606: @item providing the Block Extensions word set
13607: @item providing the Double-Number word set
13608: @item providing the Double-Number Extensions word set
13609: @item providing the Exception word set
13610: @item providing the Exception Extensions word set
13611: @item providing the Facility word set
13612: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
13613: @item providing the File Access word set
13614: @item providing the File Access Extensions word set
13615: @item providing the Floating-Point word set
13616: @item providing the Floating-Point Extensions word set
13617: @item providing the Locals word set
13618: @item providing the Locals Extensions word set
13619: @item providing the Memory-Allocation word set
13620: @item providing the Memory-Allocation Extensions word set (that one's easy)
13621: @item providing the Programming-Tools word set
13622: @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
13623: @item providing the Search-Order word set
13624: @item providing the Search-Order Extensions word set
13625: @item providing the String word set
13626: @item providing the String Extensions word set (another easy one)
13627: @end itemize
13628: 
13629: Gforth has the following environmental restrictions:
13630: 
13631: @cindex environmental restrictions
13632: @itemize @bullet
13633: @item
13634: While processing the OS command line, if an exception is not caught,
13635: Gforth exits with a non-zero exit code instyead of performing QUIT.
13636: 
13637: @item
13638: When an @code{throw} is performed after a @code{query}, Gforth does not
13639: allways restore the input source specification in effect at the
13640: corresponding catch.
13641: 
13642: @end itemize
13643: 
13644: 
13645: @cindex system documentation
13646: In addition, ANS Forth systems are required to document certain
13647: implementation choices. This chapter tries to meet these
13648: requirements. In many cases it gives a way to ask the system for the
13649: information instead of providing the information directly, in
13650: particular, if the information depends on the processor, the operating
13651: system or the installation options chosen, or if they are likely to
13652: change during the maintenance of Gforth.
13653: 
13654: @comment The framework for the rest has been taken from pfe.
13655: 
13656: @menu
13657: * The Core Words::              
13658: * The optional Block word set::  
13659: * The optional Double Number word set::  
13660: * The optional Exception word set::  
13661: * The optional Facility word set::  
13662: * The optional File-Access word set::  
13663: * The optional Floating-Point word set::  
13664: * The optional Locals word set::  
13665: * The optional Memory-Allocation word set::  
13666: * The optional Programming-Tools word set::  
13667: * The optional Search-Order word set::  
13668: @end menu
13669: 
13670: 
13671: @c =====================================================================
13672: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13673: @comment  node-name,  next,  previous,  up
13674: @section The Core Words
13675: @c =====================================================================
13676: @cindex core words, system documentation
13677: @cindex system documentation, core words
13678: 
13679: @menu
13680: * core-idef::                   Implementation Defined Options                   
13681: * core-ambcond::                Ambiguous Conditions                
13682: * core-other::                  Other System Documentation                  
13683: @end menu
13684: 
13685: @c ---------------------------------------------------------------------
13686: @node core-idef, core-ambcond, The Core Words, The Core Words
13687: @subsection Implementation Defined Options
13688: @c ---------------------------------------------------------------------
13689: @cindex core words, implementation-defined options
13690: @cindex implementation-defined options, core words
13691: 
13692: 
13693: @table @i
13694: @item (Cell) aligned addresses:
13695: @cindex cell-aligned addresses
13696: @cindex aligned addresses
13697: processor-dependent. Gforth's alignment words perform natural alignment
13698: (e.g., an address aligned for a datum of size 8 is divisible by
13699: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13700: 
13701: @item @code{EMIT} and non-graphic characters:
13702: @cindex @code{EMIT} and non-graphic characters
13703: @cindex non-graphic characters and @code{EMIT}
13704: The character is output using the C library function (actually, macro)
13705: @code{putc}.
13706: 
13707: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13708: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13709: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13710: @cindex @code{ACCEPT}, editing
13711: @cindex @code{EXPECT}, editing
13712: This is modeled on the GNU readline library (@pxref{Readline
13713: Interaction, , Command Line Editing, readline, The GNU Readline
13714: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13715: producing a full word completion every time you type it (instead of
13716: producing the common prefix of all completions). @xref{Command-line editing}.
13717: 
13718: @item character set:
13719: @cindex character set
13720: The character set of your computer and display device. Gforth is
13721: 8-bit-clean (but some other component in your system may make trouble).
13722: 
13723: @item Character-aligned address requirements:
13724: @cindex character-aligned address requirements
13725: installation-dependent. Currently a character is represented by a C
13726: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13727: (Comments on that requested).
13728: 
13729: @item character-set extensions and matching of names:
13730: @cindex character-set extensions and matching of names
13731: @cindex case-sensitivity for name lookup
13732: @cindex name lookup, case-sensitivity
13733: @cindex locale and case-sensitivity
13734: Any character except the ASCII NUL character can be used in a
13735: name. Matching is case-insensitive (except in @code{TABLE}s). The
13736: matching is performed using the C library function @code{strncasecmp}, whose
13737: function is probably influenced by the locale. E.g., the @code{C} locale
13738: does not know about accents and umlauts, so they are matched
13739: case-sensitively in that locale. For portability reasons it is best to
13740: write programs such that they work in the @code{C} locale. Then one can
13741: use libraries written by a Polish programmer (who might use words
13742: containing ISO Latin-2 encoded characters) and by a French programmer
13743: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13744: funny results for some of the words (which ones, depends on the font you
13745: are using)). Also, the locale you prefer may not be available in other
13746: operating systems. Hopefully, Unicode will solve these problems one day.
13747: 
13748: @item conditions under which control characters match a space delimiter:
13749: @cindex space delimiters
13750: @cindex control characters as delimiters
13751: If @code{word} is called with the space character as a delimiter, all
13752: white-space characters (as identified by the C macro @code{isspace()})
13753: are delimiters. @code{Parse}, on the other hand, treats space like other
13754: delimiters.  @code{Parse-name}, which is used by the outer
13755: interpreter (aka text interpreter) by default, treats all white-space
13756: characters as delimiters.
13757: 
13758: @item format of the control-flow stack:
13759: @cindex control-flow stack, format
13760: The data stack is used as control-flow stack. The size of a control-flow
13761: stack item in cells is given by the constant @code{cs-item-size}. At the
13762: time of this writing, an item consists of a (pointer to a) locals list
13763: (third), an address in the code (second), and a tag for identifying the
13764: item (TOS). The following tags are used: @code{defstart},
13765: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13766: @code{scopestart}.
13767: 
13768: @item conversion of digits > 35
13769: @cindex digits > 35
13770: The characters @code{[\]^_'} are the digits with the decimal value
13771: 36@minus{}41. There is no way to input many of the larger digits.
13772: 
13773: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13774: @cindex @code{EXPECT}, display after end of input
13775: @cindex @code{ACCEPT}, display after end of input
13776: The cursor is moved to the end of the entered string. If the input is
13777: terminated using the @kbd{Return} key, a space is typed.
13778: 
13779: @item exception abort sequence of @code{ABORT"}:
13780: @cindex exception abort sequence of @code{ABORT"}
13781: @cindex @code{ABORT"}, exception abort sequence
13782: The error string is stored into the variable @code{"error} and a
13783: @code{-2 throw} is performed.
13784: 
13785: @item input line terminator:
13786: @cindex input line terminator
13787: @cindex line terminator on input
13788: @cindex newline character on input
13789: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13790: lines. One of these characters is typically produced when you type the
13791: @kbd{Enter} or @kbd{Return} key.
13792: 
13793: @item maximum size of a counted string:
13794: @cindex maximum size of a counted string
13795: @cindex counted string, maximum size
13796: @code{s" /counted-string" environment? drop .}. Currently 255 characters
13797: on all platforms, but this may change.
13798: 
13799: @item maximum size of a parsed string:
13800: @cindex maximum size of a parsed string
13801: @cindex parsed string, maximum size
13802: Given by the constant @code{/line}. Currently 255 characters.
13803: 
13804: @item maximum size of a definition name, in characters:
13805: @cindex maximum size of a definition name, in characters
13806: @cindex name, maximum length
13807: MAXU/8
13808: 
13809: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13810: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13811: @cindex @code{ENVIRONMENT?} string length, maximum
13812: MAXU/8
13813: 
13814: @item method of selecting the user input device:
13815: @cindex user input device, method of selecting
13816: The user input device is the standard input. There is currently no way to
13817: change it from within Gforth. However, the input can typically be
13818: redirected in the command line that starts Gforth.
13819: 
13820: @item method of selecting the user output device:
13821: @cindex user output device, method of selecting
13822: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
13823: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13824: output when the user output device is a terminal, otherwise the output
13825: is buffered.
13826: 
13827: @item methods of dictionary compilation:
13828: What are we expected to document here?
13829: 
13830: @item number of bits in one address unit:
13831: @cindex number of bits in one address unit
13832: @cindex address unit, size in bits
13833: @code{s" address-units-bits" environment? drop .}. 8 in all current
13834: platforms.
13835: 
13836: @item number representation and arithmetic:
13837: @cindex number representation and arithmetic
13838: Processor-dependent. Binary two's complement on all current platforms.
13839: 
13840: @item ranges for integer types:
13841: @cindex ranges for integer types
13842: @cindex integer types, ranges
13843: Installation-dependent. Make environmental queries for @code{MAX-N},
13844: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13845: unsigned (and positive) types is 0. The lower bound for signed types on
13846: two's complement and one's complement machines machines can be computed
13847: by adding 1 to the upper bound.
13848: 
13849: @item read-only data space regions:
13850: @cindex read-only data space regions
13851: @cindex data-space, read-only regions
13852: The whole Forth data space is writable.
13853: 
13854: @item size of buffer at @code{WORD}:
13855: @cindex size of buffer at @code{WORD}
13856: @cindex @code{WORD} buffer size
13857: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13858: shared with the pictured numeric output string. If overwriting
13859: @code{PAD} is acceptable, it is as large as the remaining dictionary
13860: space, although only as much can be sensibly used as fits in a counted
13861: string.
13862: 
13863: @item size of one cell in address units:
13864: @cindex cell size
13865: @code{1 cells .}.
13866: 
13867: @item size of one character in address units:
13868: @cindex char size
13869: @code{1 chars .}. 1 on all current platforms.
13870: 
13871: @item size of the keyboard terminal buffer:
13872: @cindex size of the keyboard terminal buffer
13873: @cindex terminal buffer, size
13874: Varies. You can determine the size at a specific time using @code{lp@@
13875: tib - .}. It is shared with the locals stack and TIBs of files that
13876: include the current file. You can change the amount of space for TIBs
13877: and locals stack at Gforth startup with the command line option
13878: @code{-l}.
13879: 
13880: @item size of the pictured numeric output buffer:
13881: @cindex size of the pictured numeric output buffer
13882: @cindex pictured numeric output buffer, size
13883: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13884: shared with @code{WORD}.
13885: 
13886: @item size of the scratch area returned by @code{PAD}:
13887: @cindex size of the scratch area returned by @code{PAD}
13888: @cindex @code{PAD} size
13889: The remainder of dictionary space. @code{unused pad here - - .}.
13890: 
13891: @item system case-sensitivity characteristics:
13892: @cindex case-sensitivity characteristics
13893: Dictionary searches are case-insensitive (except in
13894: @code{TABLE}s). However, as explained above under @i{character-set
13895: extensions}, the matching for non-ASCII characters is determined by the
13896: locale you are using. In the default @code{C} locale all non-ASCII
13897: characters are matched case-sensitively.
13898: 
13899: @item system prompt:
13900: @cindex system prompt
13901: @cindex prompt
13902: @code{ ok} in interpret state, @code{ compiled} in compile state.
13903: 
13904: @item division rounding:
13905: @cindex division rounding
13906: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13907: division (with the default installation of Gforth).  You can check
13908: this with @code{s" floored" environment? drop .}.  If you write
13909: programs that need a specific division rounding, best use
13910: @code{fm/mod} or @code{sm/rem} for portability.
13911: 
13912: @item values of @code{STATE} when true:
13913: @cindex @code{STATE} values
13914: -1.
13915: 
13916: @item values returned after arithmetic overflow:
13917: On two's complement machines, arithmetic is performed modulo
13918: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13919: arithmetic (with appropriate mapping for signed types). Division by
13920: zero typically results in a @code{-55 throw} (Floating-point
13921: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
13922: division overflow can result in these throws, or in @code{-11 throw};
13923: in @code{gforth-fast} division overflow and divide by zero may also
13924: result in returning bogus results without producing an exception.
13925: 
13926: @item whether the current definition can be found after @t{DOES>}:
13927: @cindex @t{DOES>}, visibility of current definition
13928: No.
13929: 
13930: @end table
13931: 
13932: @c ---------------------------------------------------------------------
13933: @node core-ambcond, core-other, core-idef, The Core Words
13934: @subsection Ambiguous conditions
13935: @c ---------------------------------------------------------------------
13936: @cindex core words, ambiguous conditions
13937: @cindex ambiguous conditions, core words
13938: 
13939: @table @i
13940: 
13941: @item a name is neither a word nor a number:
13942: @cindex name not found
13943: @cindex undefined word
13944: @code{-13 throw} (Undefined word).
13945: 
13946: @item a definition name exceeds the maximum length allowed:
13947: @cindex word name too long
13948: @code{-19 throw} (Word name too long)
13949: 
13950: @item addressing a region not inside the various data spaces of the forth system:
13951: @cindex Invalid memory address
13952: The stacks, code space and header space are accessible. Machine code space is
13953: typically readable. Accessing other addresses gives results dependent on
13954: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13955: address).
13956: 
13957: @item argument type incompatible with parameter:
13958: @cindex argument type mismatch
13959: This is usually not caught. Some words perform checks, e.g., the control
13960: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13961: mismatch).
13962: 
13963: @item attempting to obtain the execution token of a word with undefined execution semantics:
13964: @cindex Interpreting a compile-only word, for @code{'} etc.
13965: @cindex execution token of words with undefined execution semantics
13966: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13967: get an execution token for @code{compile-only-error} (which performs a
13968: @code{-14 throw} when executed).
13969: 
13970: @item dividing by zero:
13971: @cindex dividing by zero
13972: @cindex floating point unidentified fault, integer division
13973: On some platforms, this produces a @code{-10 throw} (Division by
13974: zero); on other systems, this typically results in a @code{-55 throw}
13975: (Floating-point unidentified fault).
13976: 
13977: @item insufficient data stack or return stack space:
13978: @cindex insufficient data stack or return stack space
13979: @cindex stack overflow
13980: @cindex address alignment exception, stack overflow
13981: @cindex Invalid memory address, stack overflow
13982: Depending on the operating system, the installation, and the invocation
13983: of Gforth, this is either checked by the memory management hardware, or
13984: it is not checked. If it is checked, you typically get a @code{-3 throw}
13985: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13986: throw} (Invalid memory address) (depending on the platform and how you
13987: achieved the overflow) as soon as the overflow happens. If it is not
13988: checked, overflows typically result in mysterious illegal memory
13989: accesses, producing @code{-9 throw} (Invalid memory address) or
13990: @code{-23 throw} (Address alignment exception); they might also destroy
13991: the internal data structure of @code{ALLOCATE} and friends, resulting in
13992: various errors in these words.
13993: 
13994: @item insufficient space for loop control parameters:
13995: @cindex insufficient space for loop control parameters
13996: Like other return stack overflows.
13997: 
13998: @item insufficient space in the dictionary:
13999: @cindex insufficient space in the dictionary
14000: @cindex dictionary overflow
14001: If you try to allot (either directly with @code{allot}, or indirectly
14002: with @code{,}, @code{create} etc.) more memory than available in the
14003: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
14004: to access memory beyond the end of the dictionary, the results are
14005: similar to stack overflows.
14006: 
14007: @item interpreting a word with undefined interpretation semantics:
14008: @cindex interpreting a word with undefined interpretation semantics
14009: @cindex Interpreting a compile-only word
14010: For some words, we have defined interpretation semantics. For the
14011: others: @code{-14 throw} (Interpreting a compile-only word).
14012: 
14013: @item modifying the contents of the input buffer or a string literal:
14014: @cindex modifying the contents of the input buffer or a string literal
14015: These are located in writable memory and can be modified.
14016: 
14017: @item overflow of the pictured numeric output string:
14018: @cindex overflow of the pictured numeric output string
14019: @cindex pictured numeric output string, overflow
14020: @code{-17 throw} (Pictured numeric ouput string overflow).
14021: 
14022: @item parsed string overflow:
14023: @cindex parsed string overflow
14024: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
14025: 
14026: @item producing a result out of range:
14027: @cindex result out of range
14028: On two's complement machines, arithmetic is performed modulo
14029: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
14030: arithmetic (with appropriate mapping for signed types). Division by
14031: zero typically results in a @code{-10 throw} (divide by zero) or
14032: @code{-55 throw} (floating point unidentified fault). Overflow on
14033: division may result in these errors or in @code{-11 throw} (result out
14034: of range).  @code{Gforth-fast} may silently produce bogus results on
14035: division overflow or division by zero.  @code{Convert} and
14036: @code{>number} currently overflow silently.
14037: 
14038: @item reading from an empty data or return stack:
14039: @cindex stack empty
14040: @cindex stack underflow
14041: @cindex return stack underflow
14042: The data stack is checked by the outer (aka text) interpreter after
14043: every word executed. If it has underflowed, a @code{-4 throw} (Stack
14044: underflow) is performed. Apart from that, stacks may be checked or not,
14045: depending on operating system, installation, and invocation. If they are
14046: caught by a check, they typically result in @code{-4 throw} (Stack
14047: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
14048: (Invalid memory address), depending on the platform and which stack
14049: underflows and by how much. Note that even if the system uses checking
14050: (through the MMU), your program may have to underflow by a significant
14051: number of stack items to trigger the reaction (the reason for this is
14052: that the MMU, and therefore the checking, works with a page-size
14053: granularity).  If there is no checking, the symptoms resulting from an
14054: underflow are similar to those from an overflow.  Unbalanced return
14055: stack errors can result in a variety of symptoms, including @code{-9 throw}
14056: (Invalid memory address) and Illegal Instruction (typically @code{-260
14057: throw}).
14058: 
14059: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
14060: @cindex unexpected end of the input buffer
14061: @cindex zero-length string as a name
14062: @cindex Attempt to use zero-length string as a name
14063: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
14064: use zero-length string as a name). Words like @code{'} probably will not
14065: find what they search. Note that it is possible to create zero-length
14066: names with @code{nextname} (should it not?).
14067: 
14068: @item @code{>IN} greater than input buffer:
14069: @cindex @code{>IN} greater than input buffer
14070: The next invocation of a parsing word returns a string with length 0.
14071: 
14072: @item @code{RECURSE} appears after @code{DOES>}:
14073: @cindex @code{RECURSE} appears after @code{DOES>}
14074: Compiles a recursive call to the defining word, not to the defined word.
14075: 
14076: @item argument input source different than current input source for @code{RESTORE-INPUT}:
14077: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
14078: @cindex argument type mismatch, @code{RESTORE-INPUT}
14079: @cindex @code{RESTORE-INPUT}, Argument type mismatch
14080: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
14081: the end of the file was reached), its source-id may be
14082: reused. Therefore, restoring an input source specification referencing a
14083: closed file may lead to unpredictable results instead of a @code{-12
14084: THROW}.
14085: 
14086: In the future, Gforth may be able to restore input source specifications
14087: from other than the current input source.
14088: 
14089: @item data space containing definitions gets de-allocated:
14090: @cindex data space containing definitions gets de-allocated
14091: Deallocation with @code{allot} is not checked. This typically results in
14092: memory access faults or execution of illegal instructions.
14093: 
14094: @item data space read/write with incorrect alignment:
14095: @cindex data space read/write with incorrect alignment
14096: @cindex alignment faults
14097: @cindex address alignment exception
14098: Processor-dependent. Typically results in a @code{-23 throw} (Address
14099: alignment exception). Under Linux-Intel on a 486 or later processor with
14100: alignment turned on, incorrect alignment results in a @code{-9 throw}
14101: (Invalid memory address). There are reportedly some processors with
14102: alignment restrictions that do not report violations.
14103: 
14104: @item data space pointer not properly aligned, @code{,}, @code{C,}:
14105: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
14106: Like other alignment errors.
14107: 
14108: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
14109: Like other stack underflows.
14110: 
14111: @item loop control parameters not available:
14112: @cindex loop control parameters not available
14113: Not checked. The counted loop words simply assume that the top of return
14114: stack items are loop control parameters and behave accordingly.
14115: 
14116: @item most recent definition does not have a name (@code{IMMEDIATE}):
14117: @cindex most recent definition does not have a name (@code{IMMEDIATE})
14118: @cindex last word was headerless
14119: @code{abort" last word was headerless"}.
14120: 
14121: @item name not defined by @code{VALUE} used by @code{TO}:
14122: @cindex name not defined by @code{VALUE} used by @code{TO}
14123: @cindex @code{TO} on non-@code{VALUE}s
14124: @cindex Invalid name argument, @code{TO}
14125: @code{-32 throw} (Invalid name argument) (unless name is a local or was
14126: defined by @code{CONSTANT}; in the latter case it just changes the constant).
14127: 
14128: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
14129: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
14130: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
14131: @code{-13 throw} (Undefined word)
14132: 
14133: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
14134: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
14135: Gforth behaves as if they were of the same type. I.e., you can predict
14136: the behaviour by interpreting all parameters as, e.g., signed.
14137: 
14138: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
14139: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
14140: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
14141: compilation semantics of @code{TO}.
14142: 
14143: @item String longer than a counted string returned by @code{WORD}:
14144: @cindex string longer than a counted string returned by @code{WORD}
14145: @cindex @code{WORD}, string overflow
14146: Not checked. The string will be ok, but the count will, of course,
14147: contain only the least significant bits of the length.
14148: 
14149: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
14150: @cindex @code{LSHIFT}, large shift counts
14151: @cindex @code{RSHIFT}, large shift counts
14152: Processor-dependent. Typical behaviours are returning 0 and using only
14153: the low bits of the shift count.
14154: 
14155: @item word not defined via @code{CREATE}:
14156: @cindex @code{>BODY} of non-@code{CREATE}d words
14157: @code{>BODY} produces the PFA of the word no matter how it was defined.
14158: 
14159: @cindex @code{DOES>} of non-@code{CREATE}d words
14160: @code{DOES>} changes the execution semantics of the last defined word no
14161: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
14162: @code{CREATE , DOES>}.
14163: 
14164: @item words improperly used outside @code{<#} and @code{#>}:
14165: Not checked. As usual, you can expect memory faults.
14166: 
14167: @end table
14168: 
14169: 
14170: @c ---------------------------------------------------------------------
14171: @node core-other,  , core-ambcond, The Core Words
14172: @subsection Other system documentation
14173: @c ---------------------------------------------------------------------
14174: @cindex other system documentation, core words
14175: @cindex core words, other system documentation
14176: 
14177: @table @i
14178: @item nonstandard words using @code{PAD}:
14179: @cindex @code{PAD} use by nonstandard words
14180: None.
14181: 
14182: @item operator's terminal facilities available:
14183: @cindex operator's terminal facilities available
14184: After processing the OS's command line, Gforth goes into interactive mode,
14185: and you can give commands to Gforth interactively. The actual facilities
14186: available depend on how you invoke Gforth.
14187: 
14188: @item program data space available:
14189: @cindex program data space available
14190: @cindex data space available
14191: @code{UNUSED .} gives the remaining dictionary space. The total
14192: dictionary space can be specified with the @code{-m} switch
14193: (@pxref{Invoking Gforth}) when Gforth starts up.
14194: 
14195: @item return stack space available:
14196: @cindex return stack space available
14197: You can compute the total return stack space in cells with
14198: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
14199: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
14200: 
14201: @item stack space available:
14202: @cindex stack space available
14203: You can compute the total data stack space in cells with
14204: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
14205: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
14206: 
14207: @item system dictionary space required, in address units:
14208: @cindex system dictionary space required, in address units
14209: Type @code{here forthstart - .} after startup. At the time of this
14210: writing, this gives 80080 (bytes) on a 32-bit system.
14211: @end table
14212: 
14213: 
14214: @c =====================================================================
14215: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
14216: @section The optional Block word set
14217: @c =====================================================================
14218: @cindex system documentation, block words
14219: @cindex block words, system documentation
14220: 
14221: @menu
14222: * block-idef::                  Implementation Defined Options
14223: * block-ambcond::               Ambiguous Conditions               
14224: * block-other::                 Other System Documentation                 
14225: @end menu
14226: 
14227: 
14228: @c ---------------------------------------------------------------------
14229: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
14230: @subsection Implementation Defined Options
14231: @c ---------------------------------------------------------------------
14232: @cindex implementation-defined options, block words
14233: @cindex block words, implementation-defined options
14234: 
14235: @table @i
14236: @item the format for display by @code{LIST}:
14237: @cindex @code{LIST} display format
14238: First the screen number is displayed, then 16 lines of 64 characters,
14239: each line preceded by the line number.
14240: 
14241: @item the length of a line affected by @code{\}:
14242: @cindex length of a line affected by @code{\}
14243: @cindex @code{\}, line length in blocks
14244: 64 characters.
14245: @end table
14246: 
14247: 
14248: @c ---------------------------------------------------------------------
14249: @node block-ambcond, block-other, block-idef, The optional Block word set
14250: @subsection Ambiguous conditions
14251: @c ---------------------------------------------------------------------
14252: @cindex block words, ambiguous conditions
14253: @cindex ambiguous conditions, block words
14254: 
14255: @table @i
14256: @item correct block read was not possible:
14257: @cindex block read not possible
14258: Typically results in a @code{throw} of some OS-derived value (between
14259: -512 and -2048). If the blocks file was just not long enough, blanks are
14260: supplied for the missing portion.
14261: 
14262: @item I/O exception in block transfer:
14263: @cindex I/O exception in block transfer
14264: @cindex block transfer, I/O exception
14265: Typically results in a @code{throw} of some OS-derived value (between
14266: -512 and -2048).
14267: 
14268: @item invalid block number:
14269: @cindex invalid block number
14270: @cindex block number invalid
14271: @code{-35 throw} (Invalid block number)
14272: 
14273: @item a program directly alters the contents of @code{BLK}:
14274: @cindex @code{BLK}, altering @code{BLK}
14275: The input stream is switched to that other block, at the same
14276: position. If the storing to @code{BLK} happens when interpreting
14277: non-block input, the system will get quite confused when the block ends.
14278: 
14279: @item no current block buffer for @code{UPDATE}:
14280: @cindex @code{UPDATE}, no current block buffer
14281: @code{UPDATE} has no effect.
14282: 
14283: @end table
14284: 
14285: @c ---------------------------------------------------------------------
14286: @node block-other,  , block-ambcond, The optional Block word set
14287: @subsection Other system documentation
14288: @c ---------------------------------------------------------------------
14289: @cindex other system documentation, block words
14290: @cindex block words, other system documentation
14291: 
14292: @table @i
14293: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14294: No restrictions (yet).
14295: 
14296: @item the number of blocks available for source and data:
14297: depends on your disk space.
14298: 
14299: @end table
14300: 
14301: 
14302: @c =====================================================================
14303: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14304: @section The optional Double Number word set
14305: @c =====================================================================
14306: @cindex system documentation, double words
14307: @cindex double words, system documentation
14308: 
14309: @menu
14310: * double-ambcond::              Ambiguous Conditions              
14311: @end menu
14312: 
14313: 
14314: @c ---------------------------------------------------------------------
14315: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
14316: @subsection Ambiguous conditions
14317: @c ---------------------------------------------------------------------
14318: @cindex double words, ambiguous conditions
14319: @cindex ambiguous conditions, double words
14320: 
14321: @table @i
14322: @item @i{d} outside of range of @i{n} in @code{D>S}:
14323: @cindex @code{D>S}, @i{d} out of range of @i{n} 
14324: The least significant cell of @i{d} is produced.
14325: 
14326: @end table
14327: 
14328: 
14329: @c =====================================================================
14330: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14331: @section The optional Exception word set
14332: @c =====================================================================
14333: @cindex system documentation, exception words
14334: @cindex exception words, system documentation
14335: 
14336: @menu
14337: * exception-idef::              Implementation Defined Options              
14338: @end menu
14339: 
14340: 
14341: @c ---------------------------------------------------------------------
14342: @node exception-idef,  , The optional Exception word set, The optional Exception word set
14343: @subsection Implementation Defined Options
14344: @c ---------------------------------------------------------------------
14345: @cindex implementation-defined options, exception words
14346: @cindex exception words, implementation-defined options
14347: 
14348: @table @i
14349: @item @code{THROW}-codes used in the system:
14350: @cindex @code{THROW}-codes used in the system
14351: The codes -256@minus{}-511 are used for reporting signals. The mapping
14352: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
14353: codes -512@minus{}-2047 are used for OS errors (for file and memory
14354: allocation operations). The mapping from OS error numbers to throw codes
14355: is -512@minus{}@code{errno}. One side effect of this mapping is that
14356: undefined OS errors produce a message with a strange number; e.g.,
14357: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14358: @end table
14359: 
14360: @c =====================================================================
14361: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14362: @section The optional Facility word set
14363: @c =====================================================================
14364: @cindex system documentation, facility words
14365: @cindex facility words, system documentation
14366: 
14367: @menu
14368: * facility-idef::               Implementation Defined Options               
14369: * facility-ambcond::            Ambiguous Conditions            
14370: @end menu
14371: 
14372: 
14373: @c ---------------------------------------------------------------------
14374: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14375: @subsection Implementation Defined Options
14376: @c ---------------------------------------------------------------------
14377: @cindex implementation-defined options, facility words
14378: @cindex facility words, implementation-defined options
14379: 
14380: @table @i
14381: @item encoding of keyboard events (@code{EKEY}):
14382: @cindex keyboard events, encoding in @code{EKEY}
14383: @cindex @code{EKEY}, encoding of keyboard events
14384: Keys corresponding to ASCII characters are encoded as ASCII characters.
14385: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14386: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14387: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14388: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
14389: 
14390: 
14391: @item duration of a system clock tick:
14392: @cindex duration of a system clock tick
14393: @cindex clock tick duration
14394: System dependent. With respect to @code{MS}, the time is specified in
14395: microseconds. How well the OS and the hardware implement this, is
14396: another question.
14397: 
14398: @item repeatability to be expected from the execution of @code{MS}:
14399: @cindex repeatability to be expected from the execution of @code{MS}
14400: @cindex @code{MS}, repeatability to be expected
14401: System dependent. On Unix, a lot depends on load. If the system is
14402: lightly loaded, and the delay is short enough that Gforth does not get
14403: swapped out, the performance should be acceptable. Under MS-DOS and
14404: other single-tasking systems, it should be good.
14405: 
14406: @end table
14407: 
14408: 
14409: @c ---------------------------------------------------------------------
14410: @node facility-ambcond,  , facility-idef, The optional Facility word set
14411: @subsection Ambiguous conditions
14412: @c ---------------------------------------------------------------------
14413: @cindex facility words, ambiguous conditions
14414: @cindex ambiguous conditions, facility words
14415: 
14416: @table @i
14417: @item @code{AT-XY} can't be performed on user output device:
14418: @cindex @code{AT-XY} can't be performed on user output device
14419: Largely terminal dependent. No range checks are done on the arguments.
14420: No errors are reported. You may see some garbage appearing, you may see
14421: simply nothing happen.
14422: 
14423: @end table
14424: 
14425: 
14426: @c =====================================================================
14427: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14428: @section The optional File-Access word set
14429: @c =====================================================================
14430: @cindex system documentation, file words
14431: @cindex file words, system documentation
14432: 
14433: @menu
14434: * file-idef::                   Implementation Defined Options
14435: * file-ambcond::                Ambiguous Conditions                
14436: @end menu
14437: 
14438: @c ---------------------------------------------------------------------
14439: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14440: @subsection Implementation Defined Options
14441: @c ---------------------------------------------------------------------
14442: @cindex implementation-defined options, file words
14443: @cindex file words, implementation-defined options
14444: 
14445: @table @i
14446: @item file access methods used:
14447: @cindex file access methods used
14448: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14449: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14450: @code{wb}): The file is cleared, if it exists, and created, if it does
14451: not (with both @code{open-file} and @code{create-file}).  Under Unix
14452: @code{create-file} creates a file with 666 permissions modified by your
14453: umask.
14454: 
14455: @item file exceptions:
14456: @cindex file exceptions
14457: The file words do not raise exceptions (except, perhaps, memory access
14458: faults when you pass illegal addresses or file-ids).
14459: 
14460: @item file line terminator:
14461: @cindex file line terminator
14462: System-dependent. Gforth uses C's newline character as line
14463: terminator. What the actual character code(s) of this are is
14464: system-dependent.
14465: 
14466: @item file name format:
14467: @cindex file name format
14468: System dependent. Gforth just uses the file name format of your OS.
14469: 
14470: @item information returned by @code{FILE-STATUS}:
14471: @cindex @code{FILE-STATUS}, returned information
14472: @code{FILE-STATUS} returns the most powerful file access mode allowed
14473: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14474: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14475: along with the returned mode.
14476: 
14477: @item input file state after an exception when including source:
14478: @cindex exception when including source
14479: All files that are left via the exception are closed.
14480: 
14481: @item @i{ior} values and meaning:
14482: @cindex @i{ior} values and meaning
14483: @cindex @i{wior} values and meaning
14484: The @i{ior}s returned by the file and memory allocation words are
14485: intended as throw codes. They typically are in the range
14486: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
14487: @i{ior}s is -512@minus{}@i{errno}.
14488: 
14489: @item maximum depth of file input nesting:
14490: @cindex maximum depth of file input nesting
14491: @cindex file input nesting, maximum depth
14492: limited by the amount of return stack, locals/TIB stack, and the number
14493: of open files available. This should not give you troubles.
14494: 
14495: @item maximum size of input line:
14496: @cindex maximum size of input line
14497: @cindex input line size, maximum
14498: @code{/line}. Currently 255.
14499: 
14500: @item methods of mapping block ranges to files:
14501: @cindex mapping block ranges to files
14502: @cindex files containing blocks
14503: @cindex blocks in files
14504: By default, blocks are accessed in the file @file{blocks.fb} in the
14505: current working directory. The file can be switched with @code{USE}.
14506: 
14507: @item number of string buffers provided by @code{S"}:
14508: @cindex @code{S"}, number of string buffers
14509: 1
14510: 
14511: @item size of string buffer used by @code{S"}:
14512: @cindex @code{S"}, size of string buffer
14513: @code{/line}. currently 255.
14514: 
14515: @end table
14516: 
14517: @c ---------------------------------------------------------------------
14518: @node file-ambcond,  , file-idef, The optional File-Access word set
14519: @subsection Ambiguous conditions
14520: @c ---------------------------------------------------------------------
14521: @cindex file words, ambiguous conditions
14522: @cindex ambiguous conditions, file words
14523: 
14524: @table @i
14525: @item attempting to position a file outside its boundaries:
14526: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14527: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14528: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14529: 
14530: @item attempting to read from file positions not yet written:
14531: @cindex reading from file positions not yet written
14532: End-of-file, i.e., zero characters are read and no error is reported.
14533: 
14534: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14535: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
14536: An appropriate exception may be thrown, but a memory fault or other
14537: problem is more probable.
14538: 
14539: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14540: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14541: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14542: The @i{ior} produced by the operation, that discovered the problem, is
14543: thrown.
14544: 
14545: @item named file cannot be opened (@code{INCLUDED}):
14546: @cindex @code{INCLUDED}, named file cannot be opened
14547: The @i{ior} produced by @code{open-file} is thrown.
14548: 
14549: @item requesting an unmapped block number:
14550: @cindex unmapped block numbers
14551: There are no unmapped legal block numbers. On some operating systems,
14552: writing a block with a large number may overflow the file system and
14553: have an error message as consequence.
14554: 
14555: @item using @code{source-id} when @code{blk} is non-zero:
14556: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14557: @code{source-id} performs its function. Typically it will give the id of
14558: the source which loaded the block. (Better ideas?)
14559: 
14560: @end table
14561: 
14562: 
14563: @c =====================================================================
14564: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14565: @section The optional Floating-Point word set
14566: @c =====================================================================
14567: @cindex system documentation, floating-point words
14568: @cindex floating-point words, system documentation
14569: 
14570: @menu
14571: * floating-idef::               Implementation Defined Options
14572: * floating-ambcond::            Ambiguous Conditions            
14573: @end menu
14574: 
14575: 
14576: @c ---------------------------------------------------------------------
14577: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14578: @subsection Implementation Defined Options
14579: @c ---------------------------------------------------------------------
14580: @cindex implementation-defined options, floating-point words
14581: @cindex floating-point words, implementation-defined options
14582: 
14583: @table @i
14584: @item format and range of floating point numbers:
14585: @cindex format and range of floating point numbers
14586: @cindex floating point numbers, format and range
14587: System-dependent; the @code{double} type of C.
14588: 
14589: @item results of @code{REPRESENT} when @i{float} is out of range:
14590: @cindex  @code{REPRESENT}, results when @i{float} is out of range
14591: System dependent; @code{REPRESENT} is implemented using the C library
14592: function @code{ecvt()} and inherits its behaviour in this respect.
14593: 
14594: @item rounding or truncation of floating-point numbers:
14595: @cindex rounding of floating-point numbers
14596: @cindex truncation of floa