Annotation of gforth/doc/gforth.ds, revision 1.115

1.1       anton       1: \input texinfo   @c -*-texinfo-*-
                      2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28      crook       3: 
1.21      crook       4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28      crook       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.
1.36      anton      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
1.113     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
1.29      crook      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: 
1.66      anton      24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28      crook      25: 
1.1       anton      26: @comment %**start of header (This is for running Texinfo on a region.)
                     27: @setfilename gforth.info
1.113     anton      28: @include version.texi
1.1       anton      29: @settitle Gforth Manual
1.113     anton      30: @c @syncodeindex pg cp
1.49      anton      31: 
1.12      anton      32: @macro progstyle {}
                     33: Programming style note:
1.3       anton      34: @end macro
1.48      anton      35: 
                     36: @macro assignment {}
                     37: @table @i
                     38: @item Assignment:
                     39: @end macro
                     40: @macro endassignment {}
                     41: @end table
                     42: @end macro
                     43: 
1.29      crook      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: 
1.113     anton      57: @comment %**end of header (This is for running Texinfo on a region.)
                     58: @copying
                     59: This manual is for Gforth
                     60: (version @value{VERSION}, @value{UPDATED}),
                     61: a fast and portable implementation of the ANS Forth language
1.29      crook      62: 
1.113     anton      63: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.29      crook      64: 
1.113     anton      65: @quotation
                     66: Permission is granted to copy, distribute and/or modify this document
                     67: under the terms of the GNU Free Documentation License, Version 1.1 or
                     68: any later version published by the Free Software Foundation; with no
                     69: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
                     70: and with the Back-Cover Texts as in (a) below.  A copy of the
                     71: license is included in the section entitled ``GNU Free Documentation
                     72: License.''
                     73: 
                     74: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
                     75: this GNU Manual, like GNU software.  Copies published by the Free
                     76: Software Foundation raise funds for GNU development.''
                     77: @end quotation
                     78: @end copying
1.10      anton      79: 
1.113     anton      80: @dircategory Software development
                     81: @direntry
                     82: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     83: @end direntry
                     84: @c The Texinfo manual also recommends doing this, but for Gforth it may
                     85: @c  not make much sense
                     86: @c @dircategory Individual utilities
                     87: @c @direntry
                     88: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
                     89: @c @end direntry
1.1       anton      90: 
                     91: @titlepage
1.113     anton      92: @title Gforth
                     93: @subtitle for version @value{VERSION}, @value{UPDATED}
                     94: @author Neal Crook
                     95: @author Anton Ertl
1.114     anton      96: @author David Kuehling
1.113     anton      97: @author Bernd Paysan
                     98: @author Jens Wilke
1.1       anton      99: @page
                    100: @vskip 0pt plus 1filll
1.113     anton     101: @insertcopying
                    102: @end titlepage
1.1       anton     103: 
1.113     anton     104: @contents
1.1       anton     105: 
1.113     anton     106: @ifnottex
                    107: @node Top, Goals, (dir), (dir)
                    108: @top Gforth
1.1       anton     109: 
1.113     anton     110: @insertcopying
1.49      anton     111: @end ifnottex
1.1       anton     112: 
                    113: @menu
1.26      crook     114: * Goals::                       About the Gforth Project
1.29      crook     115: * Gforth Environment::          Starting (and exiting) Gforth
1.48      anton     116: * Tutorial::                    Hands-on Forth Tutorial
1.21      crook     117: * Introduction::                An introduction to ANS Forth
1.1       anton     118: * Words::                       Forth words available in Gforth
1.24      anton     119: * Error messages::              How to interpret them
1.1       anton     120: * Tools::                       Programming tools
                    121: * ANS conformance::             Implementation-defined options etc.
1.65      anton     122: * Standard vs Extensions::      Should I use extensions?
1.1       anton     123: * Model::                       The abstract machine of Gforth
                    124: * Integrating Gforth::          Forth as scripting language for applications
                    125: * Emacs and Gforth::            The Gforth Mode
                    126: * Image Files::                 @code{.fi} files contain compiled code
                    127: * Engine::                      The inner interpreter and the primitives
1.13      pazsan    128: * Cross Compiler::              The Cross Compiler
1.1       anton     129: * Bugs::                        How to report them
                    130: * Origin::                      Authors and ancestors of Gforth
1.21      crook     131: * Forth-related information::   Books and places to look on the WWW
1.113     anton     132: * Licenses::                    
1.1       anton     133: * Word Index::                  An item for each Forth word
                    134: * Concept Index::               A menu covering many topics
1.12      anton     135: 
1.91      anton     136: @detailmenu
                    137:  --- The Detailed Node Listing ---
1.12      anton     138: 
1.29      crook     139: Gforth Environment
                    140: 
1.32      anton     141: * Invoking Gforth::             Getting in
                    142: * Leaving Gforth::              Getting out
                    143: * Command-line editing::        
1.48      anton     144: * Environment variables::       that affect how Gforth starts up
1.32      anton     145: * Gforth Files::                What gets installed and where
1.112     anton     146: * Gforth in pipes::             
1.48      anton     147: * Startup speed::               When 35ms is not fast enough ...
                    148: 
                    149: Forth Tutorial
                    150: 
                    151: * Starting Gforth Tutorial::    
                    152: * Syntax Tutorial::             
                    153: * Crash Course Tutorial::       
                    154: * Stack Tutorial::              
                    155: * Arithmetics Tutorial::        
                    156: * Stack Manipulation Tutorial::  
                    157: * Using files for Forth code Tutorial::  
                    158: * Comments Tutorial::           
                    159: * Colon Definitions Tutorial::  
                    160: * Decompilation Tutorial::      
                    161: * Stack-Effect Comments Tutorial::  
                    162: * Types Tutorial::              
                    163: * Factoring Tutorial::          
                    164: * Designing the stack effect Tutorial::  
                    165: * Local Variables Tutorial::    
                    166: * Conditional execution Tutorial::  
                    167: * Flags and Comparisons Tutorial::  
                    168: * General Loops Tutorial::      
                    169: * Counted loops Tutorial::      
                    170: * Recursion Tutorial::          
                    171: * Leaving definitions or loops Tutorial::  
                    172: * Return Stack Tutorial::       
                    173: * Memory Tutorial::             
                    174: * Characters and Strings Tutorial::  
                    175: * Alignment Tutorial::          
1.87      anton     176: * Files Tutorial::              
1.48      anton     177: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    178: * Execution Tokens Tutorial::   
                    179: * Exceptions Tutorial::         
                    180: * Defining Words Tutorial::     
                    181: * Arrays and Records Tutorial::  
                    182: * POSTPONE Tutorial::           
                    183: * Literal Tutorial::            
                    184: * Advanced macros Tutorial::    
                    185: * Compilation Tokens Tutorial::  
                    186: * Wordlists and Search Order Tutorial::  
1.29      crook     187: 
1.24      anton     188: An Introduction to ANS Forth
                    189: 
1.67      anton     190: * Introducing the Text Interpreter::  
                    191: * Stacks and Postfix notation::  
                    192: * Your first definition::       
                    193: * How does that work?::         
                    194: * Forth is written in Forth::   
                    195: * Review - elements of a Forth system::  
                    196: * Where to go next::            
                    197: * Exercises::                   
1.24      anton     198: 
1.12      anton     199: Forth Words
                    200: 
                    201: * Notation::                    
1.65      anton     202: * Case insensitivity::          
                    203: * Comments::                    
                    204: * Boolean Flags::               
1.12      anton     205: * Arithmetic::                  
                    206: * Stack Manipulation::          
                    207: * Memory::                      
                    208: * Control Structures::          
                    209: * Defining Words::              
1.65      anton     210: * Interpretation and Compilation Semantics::  
1.47      crook     211: * Tokens for Words::            
1.81      anton     212: * Compiling words::             
1.65      anton     213: * The Text Interpreter::        
1.111     anton     214: * The Input Stream::            
1.65      anton     215: * Word Lists::                  
                    216: * Environmental Queries::       
1.12      anton     217: * Files::                       
                    218: * Blocks::                      
                    219: * Other I/O::                   
1.78      anton     220: * Locals::                      
                    221: * Structures::                  
                    222: * Object-oriented Forth::       
1.12      anton     223: * Programming Tools::           
                    224: * Assembler and Code Words::    
                    225: * Threading Words::             
1.65      anton     226: * Passing Commands to the OS::  
                    227: * Keeping track of Time::       
                    228: * Miscellaneous Words::         
1.12      anton     229: 
                    230: Arithmetic
                    231: 
                    232: * Single precision::            
1.67      anton     233: * Double precision::            Double-cell integer arithmetic
1.12      anton     234: * Bitwise operations::          
1.67      anton     235: * Numeric comparison::          
1.32      anton     236: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     237: * Floating Point::              
                    238: 
                    239: Stack Manipulation
                    240: 
                    241: * Data stack::                  
                    242: * Floating point stack::        
                    243: * Return stack::                
                    244: * Locals stack::                
                    245: * Stack pointer manipulation::  
                    246: 
                    247: Memory
                    248: 
1.32      anton     249: * Memory model::                
                    250: * Dictionary allocation::       
                    251: * Heap Allocation::             
                    252: * Memory Access::               
                    253: * Address arithmetic::          
                    254: * Memory Blocks::               
1.12      anton     255: 
                    256: Control Structures
                    257: 
1.41      anton     258: * Selection::                   IF ... ELSE ... ENDIF
                    259: * Simple Loops::                BEGIN ...
1.32      anton     260: * Counted Loops::               DO
1.67      anton     261: * Arbitrary control structures::  
                    262: * Calls and returns::           
1.12      anton     263: * Exception Handling::          
                    264: 
                    265: Defining Words
                    266: 
1.67      anton     267: * CREATE::                      
1.44      crook     268: * Variables::                   Variables and user variables
1.67      anton     269: * Constants::                   
1.44      crook     270: * Values::                      Initialised variables
1.67      anton     271: * Colon Definitions::           
1.44      crook     272: * Anonymous Definitions::       Definitions without names
1.71      anton     273: * Supplying names::             Passing definition names as strings
1.67      anton     274: * User-defined Defining Words::  
1.44      crook     275: * Deferred words::              Allow forward references
1.67      anton     276: * Aliases::                     
1.47      crook     277: 
1.63      anton     278: User-defined Defining Words
                    279: 
                    280: * CREATE..DOES> applications::  
                    281: * CREATE..DOES> details::       
                    282: * Advanced does> usage example::  
1.91      anton     283: * @code{Const-does>}::          
1.63      anton     284: 
1.47      crook     285: Interpretation and Compilation Semantics
                    286: 
1.67      anton     287: * Combined words::              
1.12      anton     288: 
1.71      anton     289: Tokens for Words
                    290: 
                    291: * Execution token::             represents execution/interpretation semantics
                    292: * Compilation token::           represents compilation semantics
                    293: * Name token::                  represents named words
                    294: 
1.82      anton     295: Compiling words
                    296: 
                    297: * Literals::                    Compiling data values
                    298: * Macros::                      Compiling words
                    299: 
1.21      crook     300: The Text Interpreter
                    301: 
1.67      anton     302: * Input Sources::               
                    303: * Number Conversion::           
                    304: * Interpret/Compile states::    
                    305: * Interpreter Directives::      
1.21      crook     306: 
1.26      crook     307: Word Lists
                    308: 
1.75      anton     309: * Vocabularies::                
1.67      anton     310: * Why use word lists?::         
1.75      anton     311: * Word list example::           
1.26      crook     312: 
                    313: Files
                    314: 
1.48      anton     315: * Forth source files::          
                    316: * General files::               
                    317: * Search Paths::                
                    318: 
                    319: Search Paths
                    320: 
1.75      anton     321: * Source Search Paths::         
1.26      crook     322: * General Search Paths::        
                    323: 
                    324: Other I/O
                    325: 
1.32      anton     326: * Simple numeric output::       Predefined formats
                    327: * Formatted numeric output::    Formatted (pictured) output
                    328: * String Formats::              How Forth stores strings in memory
1.67      anton     329: * Displaying characters and strings::  Other stuff
1.32      anton     330: * Input::                       Input
1.112     anton     331: * Pipes::                       How to create your own pipes
1.26      crook     332: 
                    333: Locals
                    334: 
                    335: * Gforth locals::               
                    336: * ANS Forth locals::            
                    337: 
                    338: Gforth locals
                    339: 
                    340: * Where are locals visible by name?::  
                    341: * How long do locals live?::    
1.78      anton     342: * Locals programming style::    
                    343: * Locals implementation::       
1.26      crook     344: 
1.12      anton     345: Structures
                    346: 
                    347: * Why explicit structure support?::  
                    348: * Structure Usage::             
                    349: * Structure Naming Convention::  
                    350: * Structure Implementation::    
                    351: * Structure Glossary::          
                    352: 
                    353: Object-oriented Forth
                    354: 
1.48      anton     355: * Why object-oriented programming?::  
                    356: * Object-Oriented Terminology::  
                    357: * Objects::                     
                    358: * OOF::                         
                    359: * Mini-OOF::                    
1.23      crook     360: * Comparison with other object models::  
1.12      anton     361: 
1.24      anton     362: The @file{objects.fs} model
1.12      anton     363: 
                    364: * Properties of the Objects model::  
                    365: * Basic Objects Usage::         
1.41      anton     366: * The Objects base class::      
1.12      anton     367: * Creating objects::            
                    368: * Object-Oriented Programming Style::  
                    369: * Class Binding::               
                    370: * Method conveniences::         
                    371: * Classes and Scoping::         
1.41      anton     372: * Dividing classes::            
1.12      anton     373: * Object Interfaces::           
                    374: * Objects Implementation::      
                    375: * Objects Glossary::            
                    376: 
1.24      anton     377: The @file{oof.fs} model
1.12      anton     378: 
1.67      anton     379: * Properties of the OOF model::  
                    380: * Basic OOF Usage::             
                    381: * The OOF base class::          
                    382: * Class Declaration::           
                    383: * Class Implementation::        
1.12      anton     384: 
1.24      anton     385: The @file{mini-oof.fs} model
1.23      crook     386: 
1.48      anton     387: * Basic Mini-OOF Usage::        
                    388: * Mini-OOF Example::            
                    389: * Mini-OOF Implementation::     
1.23      crook     390: 
1.78      anton     391: Programming Tools
                    392: 
                    393: * Examining::                   
                    394: * Forgetting words::            
                    395: * Debugging::                   Simple and quick.
                    396: * Assertions::                  Making your programs self-checking.
                    397: * Singlestep Debugger::         Executing your program word by word.
                    398: 
                    399: Assembler and Code Words
                    400: 
                    401: * Code and ;code::              
                    402: * Common Assembler::            Assembler Syntax
                    403: * Common Disassembler::         
                    404: * 386 Assembler::               Deviations and special cases
                    405: * Alpha Assembler::             Deviations and special cases
                    406: * MIPS assembler::              Deviations and special cases
                    407: * Other assemblers::            How to write them
                    408: 
1.12      anton     409: Tools
                    410: 
                    411: * ANS Report::                  Report the words used, sorted by wordset.
                    412: 
                    413: ANS conformance
                    414: 
                    415: * The Core Words::              
                    416: * The optional Block word set::  
                    417: * The optional Double Number word set::  
                    418: * The optional Exception word set::  
                    419: * The optional Facility word set::  
                    420: * The optional File-Access word set::  
                    421: * The optional Floating-Point word set::  
                    422: * The optional Locals word set::  
                    423: * The optional Memory-Allocation word set::  
                    424: * The optional Programming-Tools word set::  
                    425: * The optional Search-Order word set::  
                    426: 
                    427: The Core Words
                    428: 
                    429: * core-idef::                   Implementation Defined Options                   
                    430: * core-ambcond::                Ambiguous Conditions                
                    431: * core-other::                  Other System Documentation                  
                    432: 
                    433: The optional Block word set
                    434: 
                    435: * block-idef::                  Implementation Defined Options
                    436: * block-ambcond::               Ambiguous Conditions               
                    437: * block-other::                 Other System Documentation                 
                    438: 
                    439: The optional Double Number word set
                    440: 
                    441: * double-ambcond::              Ambiguous Conditions              
                    442: 
                    443: The optional Exception word set
                    444: 
                    445: * exception-idef::              Implementation Defined Options              
                    446: 
                    447: The optional Facility word set
                    448: 
                    449: * facility-idef::               Implementation Defined Options               
                    450: * facility-ambcond::            Ambiguous Conditions            
                    451: 
                    452: The optional File-Access word set
                    453: 
                    454: * file-idef::                   Implementation Defined Options
                    455: * file-ambcond::                Ambiguous Conditions                
                    456: 
                    457: The optional Floating-Point word set
                    458: 
                    459: * floating-idef::               Implementation Defined Options
                    460: * floating-ambcond::            Ambiguous Conditions            
                    461: 
                    462: The optional Locals word set
                    463: 
                    464: * locals-idef::                 Implementation Defined Options                 
                    465: * locals-ambcond::              Ambiguous Conditions              
                    466: 
                    467: The optional Memory-Allocation word set
                    468: 
                    469: * memory-idef::                 Implementation Defined Options                 
                    470: 
                    471: The optional Programming-Tools word set
                    472: 
                    473: * programming-idef::            Implementation Defined Options            
                    474: * programming-ambcond::         Ambiguous Conditions         
                    475: 
                    476: The optional Search-Order word set
                    477: 
                    478: * search-idef::                 Implementation Defined Options                 
                    479: * search-ambcond::              Ambiguous Conditions              
                    480: 
1.109     anton     481: Emacs and Gforth
                    482: 
                    483: * Installing gforth.el::        Making Emacs aware of Forth.
                    484: * Emacs Tags::                  Viewing the source of a word in Emacs.
                    485: * Hilighting::                  Making Forth code look prettier.
                    486: * Auto-Indentation::            Customizing auto-indentation.
                    487: * Blocks Files::                Reading and writing blocks files.
                    488: 
1.12      anton     489: Image Files
                    490: 
1.24      anton     491: * Image Licensing Issues::      Distribution terms for images.
                    492: * Image File Background::       Why have image files?
1.67      anton     493: * Non-Relocatable Image Files::  don't always work.
1.24      anton     494: * Data-Relocatable Image Files::  are better.
1.67      anton     495: * Fully Relocatable Image Files::  better yet.
1.24      anton     496: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     497: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     498: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     499: 
                    500: Fully Relocatable Image Files
                    501: 
1.27      crook     502: * gforthmi::                    The normal way
1.12      anton     503: * cross.fs::                    The hard way
                    504: 
                    505: Engine
                    506: 
                    507: * Portability::                 
                    508: * Threading::                   
                    509: * Primitives::                  
                    510: * Performance::                 
                    511: 
                    512: Threading
                    513: 
                    514: * Scheduling::                  
                    515: * Direct or Indirect Threaded?::  
1.109     anton     516: * Dynamic Superinstructions::   
1.12      anton     517: * DOES>::                       
                    518: 
                    519: Primitives
                    520: 
                    521: * Automatic Generation::        
                    522: * TOS Optimization::            
                    523: * Produced code::               
1.13      pazsan    524: 
                    525: Cross Compiler
                    526: 
1.67      anton     527: * Using the Cross Compiler::    
                    528: * How the Cross Compiler Works::  
1.13      pazsan    529: 
1.113     anton     530: Licenses
                    531: 
                    532: * GNU Free Documentation License::  License for copying this manual.
                    533: * Copying::                         GPL (for copying this software).
                    534: 
1.24      anton     535: @end detailmenu
1.1       anton     536: @end menu
                    537: 
1.113     anton     538: @c ----------------------------------------------------------
1.1       anton     539: @iftex
                    540: @unnumbered Preface
                    541: @cindex Preface
1.21      crook     542: This manual documents Gforth. Some introductory material is provided for
                    543: readers who are unfamiliar with Forth or who are migrating to Gforth
                    544: from other Forth compilers. However, this manual is primarily a
                    545: reference manual.
1.1       anton     546: @end iftex
                    547: 
1.28      crook     548: @comment TODO much more blurb here.
1.26      crook     549: 
                    550: @c ******************************************************************
1.113     anton     551: @node Goals, Gforth Environment, Top, Top
1.26      crook     552: @comment node-name,     next,           previous, up
                    553: @chapter Goals of Gforth
                    554: @cindex goals of the Gforth project
                    555: The goal of the Gforth Project is to develop a standard model for
                    556: ANS Forth. This can be split into several subgoals:
                    557: 
                    558: @itemize @bullet
                    559: @item
                    560: Gforth should conform to the ANS Forth Standard.
                    561: @item
                    562: It should be a model, i.e. it should define all the
                    563: implementation-dependent things.
                    564: @item
                    565: It should become standard, i.e. widely accepted and used. This goal
                    566: is the most difficult one.
                    567: @end itemize
                    568: 
                    569: To achieve these goals Gforth should be
                    570: @itemize @bullet
                    571: @item
                    572: Similar to previous models (fig-Forth, F83)
                    573: @item
                    574: Powerful. It should provide for all the things that are considered
                    575: necessary today and even some that are not yet considered necessary.
                    576: @item
                    577: Efficient. It should not get the reputation of being exceptionally
                    578: slow.
                    579: @item
                    580: Free.
                    581: @item
                    582: Available on many machines/easy to port.
                    583: @end itemize
                    584: 
                    585: Have we achieved these goals? Gforth conforms to the ANS Forth
                    586: standard. It may be considered a model, but we have not yet documented
                    587: which parts of the model are stable and which parts we are likely to
                    588: change. It certainly has not yet become a de facto standard, but it
                    589: appears to be quite popular. It has some similarities to and some
                    590: differences from previous models. It has some powerful features, but not
                    591: yet everything that we envisioned. We certainly have achieved our
1.65      anton     592: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    593: the bar was raised when the major commercial Forth vendors switched to
                    594: native code compilers.}.  It is free and available on many machines.
1.29      crook     595: 
1.26      crook     596: @c ******************************************************************
1.48      anton     597: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook     598: @chapter Gforth Environment
                    599: @cindex Gforth environment
1.21      crook     600: 
1.45      crook     601: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook     602: material in this chapter.
1.21      crook     603: 
                    604: @menu
1.29      crook     605: * Invoking Gforth::             Getting in
                    606: * Leaving Gforth::              Getting out
                    607: * Command-line editing::        
1.48      anton     608: * Environment variables::       that affect how Gforth starts up
1.29      crook     609: * Gforth Files::                What gets installed and where
1.112     anton     610: * Gforth in pipes::             
1.48      anton     611: * Startup speed::               When 35ms is not fast enough ...
1.21      crook     612: @end menu
                    613: 
1.49      anton     614: For related information about the creation of images see @ref{Image Files}.
1.29      crook     615: 
1.21      crook     616: @comment ----------------------------------------------
1.48      anton     617: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook     618: @section Invoking Gforth
                    619: @cindex invoking Gforth
                    620: @cindex running Gforth
                    621: @cindex command-line options
                    622: @cindex options on the command line
                    623: @cindex flags on the command line
1.21      crook     624: 
1.30      anton     625: Gforth is made up of two parts; an executable ``engine'' (named
1.109     anton     626: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30      anton     627: will usually just say @code{gforth} -- this automatically loads the
                    628: default image file @file{gforth.fi}. In many other cases the default
                    629: Gforth image will be invoked like this:
1.21      crook     630: @example
1.30      anton     631: gforth [file | -e forth-code] ...
1.21      crook     632: @end example
1.29      crook     633: @noindent
                    634: This interprets the contents of the files and the Forth code in the order they
                    635: are given.
1.21      crook     636: 
1.109     anton     637: In addition to the @command{gforth} engine, there is also an engine
                    638: called @command{gforth-fast}, which is faster, but gives less
                    639: informative error messages (@pxref{Error messages}) and may catch some
                    640: stack underflows later or not at all.  You should use it for debugged,
                    641: performance-critical programs.
                    642: 
                    643: Moreover, there is an engine called @command{gforth-itc}, which is
                    644: useful in some backwards-compatibility situations (@pxref{Direct or
                    645: Indirect Threaded?}).
1.30      anton     646: 
1.29      crook     647: In general, the command line looks like this:
1.21      crook     648: 
                    649: @example
1.30      anton     650: gforth[-fast] [engine options] [image options]
1.21      crook     651: @end example
                    652: 
1.30      anton     653: The engine options must come before the rest of the command
1.29      crook     654: line. They are:
1.26      crook     655: 
1.29      crook     656: @table @code
                    657: @cindex -i, command-line option
                    658: @cindex --image-file, command-line option
                    659: @item --image-file @i{file}
                    660: @itemx -i @i{file}
                    661: Loads the Forth image @i{file} instead of the default
                    662: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook     663: 
1.39      anton     664: @cindex --appl-image, command-line option
                    665: @item --appl-image @i{file}
                    666: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton     667: to the image (instead of processing them as engine options).  This is
                    668: useful for building executable application images on Unix, built with
1.39      anton     669: @code{gforthmi --application ...}.
                    670: 
1.29      crook     671: @cindex --path, command-line option
                    672: @cindex -p, command-line option
                    673: @item --path @i{path}
                    674: @itemx -p @i{path}
                    675: Uses @i{path} for searching the image file and Forth source code files
                    676: instead of the default in the environment variable @code{GFORTHPATH} or
                    677: the path specified at installation time (e.g.,
                    678: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                    679: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook     680: 
1.29      crook     681: @cindex --dictionary-size, command-line option
                    682: @cindex -m, command-line option
                    683: @cindex @i{size} parameters for command-line options
                    684: @cindex size of the dictionary and the stacks
                    685: @item --dictionary-size @i{size}
                    686: @itemx -m @i{size}
                    687: Allocate @i{size} space for the Forth dictionary space instead of
                    688: using the default specified in the image (typically 256K). The
                    689: @i{size} specification for this and subsequent options consists of
                    690: an integer and a unit (e.g.,
                    691: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                    692: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                    693: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                    694: @code{e} is used.
1.21      crook     695: 
1.29      crook     696: @cindex --data-stack-size, command-line option
                    697: @cindex -d, command-line option
                    698: @item --data-stack-size @i{size}
                    699: @itemx -d @i{size}
                    700: Allocate @i{size} space for the data stack instead of using the
                    701: default specified in the image (typically 16K).
1.21      crook     702: 
1.29      crook     703: @cindex --return-stack-size, command-line option
                    704: @cindex -r, command-line option
                    705: @item --return-stack-size @i{size}
                    706: @itemx -r @i{size}
                    707: Allocate @i{size} space for the return stack instead of using the
                    708: default specified in the image (typically 15K).
1.21      crook     709: 
1.29      crook     710: @cindex --fp-stack-size, command-line option
                    711: @cindex -f, command-line option
                    712: @item --fp-stack-size @i{size}
                    713: @itemx -f @i{size}
                    714: Allocate @i{size} space for the floating point stack instead of
                    715: using the default specified in the image (typically 15.5K). In this case
                    716: the unit specifier @code{e} refers to floating point numbers.
1.21      crook     717: 
1.48      anton     718: @cindex --locals-stack-size, command-line option
                    719: @cindex -l, command-line option
                    720: @item --locals-stack-size @i{size}
                    721: @itemx -l @i{size}
                    722: Allocate @i{size} space for the locals stack instead of using the
                    723: default specified in the image (typically 14.5K).
                    724: 
                    725: @cindex -h, command-line option
                    726: @cindex --help, command-line option
                    727: @item --help
                    728: @itemx -h
                    729: Print a message about the command-line options
                    730: 
                    731: @cindex -v, command-line option
                    732: @cindex --version, command-line option
                    733: @item --version
                    734: @itemx -v
                    735: Print version and exit
                    736: 
                    737: @cindex --debug, command-line option
                    738: @item --debug
                    739: Print some information useful for debugging on startup.
                    740: 
                    741: @cindex --offset-image, command-line option
                    742: @item --offset-image
                    743: Start the dictionary at a slightly different position than would be used
                    744: otherwise (useful for creating data-relocatable images,
                    745: @pxref{Data-Relocatable Image Files}).
                    746: 
                    747: @cindex --no-offset-im, command-line option
                    748: @item --no-offset-im
                    749: Start the dictionary at the normal position.
                    750: 
                    751: @cindex --clear-dictionary, command-line option
                    752: @item --clear-dictionary
                    753: Initialize all bytes in the dictionary to 0 before loading the image
                    754: (@pxref{Data-Relocatable Image Files}).
                    755: 
                    756: @cindex --die-on-signal, command-line-option
                    757: @item --die-on-signal
                    758: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                    759: or the segmentation violation SIGSEGV) by translating it into a Forth
                    760: @code{THROW}. With this option, Gforth exits if it receives such a
                    761: signal. This option is useful when the engine and/or the image might be
                    762: severely broken (such that it causes another signal before recovering
                    763: from the first); this option avoids endless loops in such cases.
1.109     anton     764: 
                    765: @item --no-dynamic
                    766: @item --dynamic
                    767: Disable or enable dynamic superinstructions with replication
                    768: (@pxref{Dynamic Superinstructions}).
                    769: 
                    770: @item --no-super
1.110     anton     771: Disable dynamic superinstructions, use just dynamic replication; this is
                    772: useful if you want to patch threaded code (@pxref{Dynamic
                    773: Superinstructions}).
1.109     anton     774: 
1.48      anton     775: @end table
                    776: 
                    777: @cindex loading files at startup
                    778: @cindex executing code on startup
                    779: @cindex batch processing with Gforth
                    780: As explained above, the image-specific command-line arguments for the
                    781: default image @file{gforth.fi} consist of a sequence of filenames and
                    782: @code{-e @var{forth-code}} options that are interpreted in the sequence
                    783: in which they are given. The @code{-e @var{forth-code}} or
                    784: @code{--evaluate @var{forth-code}} option evaluates the Forth
                    785: code. This option takes only one argument; if you want to evaluate more
                    786: Forth words, you have to quote them or use @code{-e} several times. To exit
                    787: after processing the command line (instead of entering interactive mode)
                    788: append @code{-e bye} to the command line.
                    789: 
                    790: @cindex versions, invoking other versions of Gforth
                    791: If you have several versions of Gforth installed, @code{gforth} will
                    792: invoke the version that was installed last. @code{gforth-@i{version}}
                    793: invokes a specific version. If your environment contains the variable
                    794: @code{GFORTHPATH}, you may want to override it by using the
                    795: @code{--path} option.
                    796: 
                    797: Not yet implemented:
                    798: On startup the system first executes the system initialization file
                    799: (unless the option @code{--no-init-file} is given; note that the system
                    800: resulting from using this option may not be ANS Forth conformant). Then
                    801: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook     802: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton     803: then in @file{~}, then in the normal path (see above).
                    804: 
                    805: 
                    806: 
                    807: @comment ----------------------------------------------
                    808: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                    809: @section Leaving Gforth
                    810: @cindex Gforth - leaving
                    811: @cindex leaving Gforth
                    812: 
                    813: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                    814: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                    815: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton     816: data are discarded.  For ways of saving the state of the system before
                    817: leaving Gforth see @ref{Image Files}.
1.48      anton     818: 
                    819: doc-bye
                    820: 
                    821: 
                    822: @comment ----------------------------------------------
1.65      anton     823: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton     824: @section Command-line editing
                    825: @cindex command-line editing
                    826: 
                    827: Gforth maintains a history file that records every line that you type to
                    828: the text interpreter. This file is preserved between sessions, and is
                    829: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                    830: repeatedly you can recall successively older commands from this (or
                    831: previous) session(s). The full list of command-line editing facilities is:
                    832: 
                    833: @itemize @bullet
                    834: @item
                    835: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                    836: commands from the history buffer.
                    837: @item
                    838: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                    839: from the history buffer.
                    840: @item
                    841: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                    842: @item
                    843: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                    844: @item
                    845: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                    846: closing up the line.
                    847: @item
                    848: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                    849: @item
                    850: @kbd{Ctrl-a} to move the cursor to the start of the line.
                    851: @item
                    852: @kbd{Ctrl-e} to move the cursor to the end of the line.
                    853: @item
                    854: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                    855: line.
                    856: @item
                    857: @key{TAB} to step through all possible full-word completions of the word
                    858: currently being typed.
                    859: @item
1.65      anton     860: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                    861: using @code{bye}). 
                    862: @item
                    863: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                    864: character under the cursor.
1.48      anton     865: @end itemize
                    866: 
                    867: When editing, displayable characters are inserted to the left of the
                    868: cursor position; the line is always in ``insert'' (as opposed to
                    869: ``overstrike'') mode.
                    870: 
                    871: @cindex history file
                    872: @cindex @file{.gforth-history}
                    873: On Unix systems, the history file is @file{~/.gforth-history} by
                    874: default@footnote{i.e. it is stored in the user's home directory.}. You
                    875: can find out the name and location of your history file using:
                    876: 
                    877: @example 
                    878: history-file type \ Unix-class systems
                    879: 
                    880: history-file type \ Other systems
                    881: history-dir  type
                    882: @end example
                    883: 
                    884: If you enter long definitions by hand, you can use a text editor to
                    885: paste them out of the history file into a Forth source file for reuse at
                    886: a later time.
                    887: 
                    888: Gforth never trims the size of the history file, so you should do this
                    889: periodically, if necessary.
                    890: 
                    891: @comment this is all defined in history.fs
                    892: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                    893: @comment chosen?
                    894: 
                    895: 
                    896: @comment ----------------------------------------------
1.65      anton     897: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton     898: @section Environment variables
                    899: @cindex environment variables
                    900: 
                    901: Gforth uses these environment variables:
                    902: 
                    903: @itemize @bullet
                    904: @item
                    905: @cindex @code{GFORTHHIST} -- environment variable
                    906: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                    907: open/create the history file, @file{.gforth-history}. Default:
                    908: @code{$HOME}.
                    909: 
                    910: @item
                    911: @cindex @code{GFORTHPATH} -- environment variable
                    912: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                    913: for Forth source-code files.
                    914: 
                    915: @item
                    916: @cindex @code{GFORTH} -- environment variable
1.49      anton     917: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton     918: 
                    919: @item
                    920: @cindex @code{GFORTHD} -- environment variable
1.62      crook     921: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton     922: 
                    923: @item
                    924: @cindex @code{TMP}, @code{TEMP} - environment variable
                    925: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                    926: location for the history file.
                    927: @end itemize
                    928: 
                    929: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                    930: @comment mentioning these.
                    931: 
                    932: All the Gforth environment variables default to sensible values if they
                    933: are not set.
                    934: 
                    935: 
                    936: @comment ----------------------------------------------
1.112     anton     937: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48      anton     938: @section Gforth files
                    939: @cindex Gforth files
                    940: 
                    941: When you install Gforth on a Unix system, it installs files in these
                    942: locations by default:
                    943: 
                    944: @itemize @bullet
                    945: @item
                    946: @file{/usr/local/bin/gforth}
                    947: @item
                    948: @file{/usr/local/bin/gforthmi}
                    949: @item
                    950: @file{/usr/local/man/man1/gforth.1} - man page.
                    951: @item
                    952: @file{/usr/local/info} - the Info version of this manual.
                    953: @item
                    954: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                    955: @item
                    956: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                    957: @item
                    958: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                    959: @item
                    960: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                    961: @end itemize
                    962: 
                    963: You can select different places for installation by using
                    964: @code{configure} options (listed with @code{configure --help}).
                    965: 
                    966: @comment ----------------------------------------------
1.112     anton     967: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
                    968: @section Gforth in pipes
                    969: @cindex pipes, Gforth as part of
                    970: 
                    971: Gforth can be used in pipes created elsewhere (described here).  It can
                    972: also create pipes on its own (@pxref{Pipes}).
                    973: 
                    974: @cindex input from pipes
                    975: If you pipe into Gforth, your program should read with @code{read-file}
                    976: or @code{read-line} from @code{stdin} (@pxref{General files}).
                    977: @code{Key} does not recognize the end of input.  Words like
                    978: @code{accept} echo the input and are therefore usually not useful for
                    979: reading from a pipe.  You have to invoke the Forth program with an OS
                    980: command-line option, as you have no chance to use the Forth command line
                    981: (the text interpreter would try to interpret the pipe input).
                    982: 
                    983: @cindex output in pipes
                    984: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
                    985: 
                    986: @cindex silent exiting from Gforth
                    987: When you write to a pipe that has been closed at the other end, Gforth
                    988: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
                    989: into the exception @code{broken-pipe-error}.  If your application does
                    990: not catch that exception, the system catches it and exits, usually
                    991: silently (unless you were working on the Forth command line; then it
                    992: prints an error message and exits).  This is usually the desired
                    993: behaviour.
                    994: 
                    995: If you do not like this behaviour, you have to catch the exception
                    996: yourself, and react to it.
                    997: 
                    998: Here's an example of an invocation of Gforth that is usable in a pipe:
                    999: 
                   1000: @example
                   1001: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
                   1002:  type repeat ; foo bye"
                   1003: @end example
                   1004: 
                   1005: This example just copies the input verbatim to the output.  A very
                   1006: simple pipe containing this example looks like this:
                   1007: 
                   1008: @example
                   1009: cat startup.fs |
                   1010: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
                   1011:  type repeat ; foo bye"|
                   1012: head
                   1013: @end example
                   1014: 
                   1015: @cindex stderr and pipes
                   1016: Pipes involving Gforth's @code{stderr} output do not work.
                   1017: 
                   1018: @comment ----------------------------------------------
                   1019: @node Startup speed,  , Gforth in pipes, Gforth Environment
1.48      anton    1020: @section Startup speed
                   1021: @cindex Startup speed
                   1022: @cindex speed, startup
                   1023: 
                   1024: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1025: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1026: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1027: system time.
                   1028: 
                   1029: If startup speed is a problem, you may consider the following ways to
                   1030: improve it; or you may consider ways to reduce the number of startups
1.62      crook    1031: (for example, by using Fast-CGI).
1.48      anton    1032: 
1.112     anton    1033: An easy step that influences Gforth startup speed is the use of the
                   1034: @option{--no-dynamic} option; this decreases image loading speed, but
                   1035: increases compile-time and run-time.
                   1036: 
                   1037: Another step to improve startup speed is to statically link Gforth, by
1.48      anton    1038: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1039: the code and will therefore slow down the first invocation, but
                   1040: subsequent invocations avoid the dynamic linking overhead.  Another
                   1041: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1042: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1043: 8.2ms system time.
                   1044: 
                   1045: The next step to improve startup speed is to use a non-relocatable image
1.65      anton    1046: (@pxref{Non-Relocatable Image Files}).  You can create this image with
1.48      anton    1047: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1048: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1049: and a part of the copy-on-write overhead.  The disadvantage is that the
1.62      crook    1050: non-relocatable image does not work if the OS gives Gforth a different
1.48      anton    1051: address for the dictionary, for whatever reason; so you better provide a
                   1052: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1053: bye} takes about 15.3ms user and 7.5ms system time.
                   1054: 
                   1055: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1056: builds the hash table on startup, which takes much of the startup
                   1057: overhead. You can do this by commenting out the @code{include hash.fs}
                   1058: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1059: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1060: The disadvantages are that functionality like @code{table} and
                   1061: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1062: now takes much longer. So, you should only use this method if there is
                   1063: no significant text interpretation to perform (the script should be
1.62      crook    1064: compiled into the image, amongst other things).  @code{gforth-static -i
1.48      anton    1065: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1066: 
                   1067: @c ******************************************************************
                   1068: @node Tutorial, Introduction, Gforth Environment, Top
                   1069: @chapter Forth Tutorial
                   1070: @cindex Tutorial
                   1071: @cindex Forth Tutorial
                   1072: 
1.67      anton    1073: @c Topics from nac's Introduction that could be mentioned:
                   1074: @c press <ret> after each line
                   1075: @c Prompt
                   1076: @c numbers vs. words in dictionary on text interpretation
                   1077: @c what happens on redefinition
                   1078: @c parsing words (in particular, defining words)
                   1079: 
1.83      anton    1080: The difference of this chapter from the Introduction
                   1081: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1082: be used while sitting in front of a computer, and covers much more
                   1083: material, but does not explain how the Forth system works.
                   1084: 
1.62      crook    1085: This tutorial can be used with any ANS-compliant Forth; any
                   1086: Gforth-specific features are marked as such and you can skip them if you
                   1087: work with another Forth.  This tutorial does not explain all features of
                   1088: Forth, just enough to get you started and give you some ideas about the
                   1089: facilities available in Forth.  Read the rest of the manual and the
                   1090: standard when you are through this.
1.48      anton    1091: 
                   1092: The intended way to use this tutorial is that you work through it while
                   1093: sitting in front of the console, take a look at the examples and predict
                   1094: what they will do, then try them out; if the outcome is not as expected,
                   1095: find out why (e.g., by trying out variations of the example), so you
                   1096: understand what's going on.  There are also some assignments that you
                   1097: should solve.
                   1098: 
                   1099: This tutorial assumes that you have programmed before and know what,
                   1100: e.g., a loop is.
                   1101: 
                   1102: @c !! explain compat library
                   1103: 
                   1104: @menu
                   1105: * Starting Gforth Tutorial::    
                   1106: * Syntax Tutorial::             
                   1107: * Crash Course Tutorial::       
                   1108: * Stack Tutorial::              
                   1109: * Arithmetics Tutorial::        
                   1110: * Stack Manipulation Tutorial::  
                   1111: * Using files for Forth code Tutorial::  
                   1112: * Comments Tutorial::           
                   1113: * Colon Definitions Tutorial::  
                   1114: * Decompilation Tutorial::      
                   1115: * Stack-Effect Comments Tutorial::  
                   1116: * Types Tutorial::              
                   1117: * Factoring Tutorial::          
                   1118: * Designing the stack effect Tutorial::  
                   1119: * Local Variables Tutorial::    
                   1120: * Conditional execution Tutorial::  
                   1121: * Flags and Comparisons Tutorial::  
                   1122: * General Loops Tutorial::      
                   1123: * Counted loops Tutorial::      
                   1124: * Recursion Tutorial::          
                   1125: * Leaving definitions or loops Tutorial::  
                   1126: * Return Stack Tutorial::       
                   1127: * Memory Tutorial::             
                   1128: * Characters and Strings Tutorial::  
                   1129: * Alignment Tutorial::          
1.87      anton    1130: * Files Tutorial::              
1.48      anton    1131: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1132: * Execution Tokens Tutorial::   
                   1133: * Exceptions Tutorial::         
                   1134: * Defining Words Tutorial::     
                   1135: * Arrays and Records Tutorial::  
                   1136: * POSTPONE Tutorial::           
                   1137: * Literal Tutorial::            
                   1138: * Advanced macros Tutorial::    
                   1139: * Compilation Tokens Tutorial::  
                   1140: * Wordlists and Search Order Tutorial::  
                   1141: @end menu
                   1142: 
                   1143: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1144: @section Starting Gforth
1.66      anton    1145: @cindex starting Gforth tutorial
1.48      anton    1146: You can start Gforth by typing its name:
                   1147: 
                   1148: @example
                   1149: gforth
                   1150: @end example
                   1151: 
                   1152: That puts you into interactive mode; you can leave Gforth by typing
                   1153: @code{bye}.  While in Gforth, you can edit the command line and access
                   1154: the command line history with cursor keys, similar to bash.
                   1155: 
                   1156: 
                   1157: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1158: @section Syntax
1.66      anton    1159: @cindex syntax tutorial
1.48      anton    1160: 
                   1161: A @dfn{word} is a sequence of arbitrary characters (expcept white
                   1162: space).  Words are separated by white space.  E.g., each of the
                   1163: following lines contains exactly one word:
                   1164: 
                   1165: @example
                   1166: word
                   1167: !@@#$%^&*()
                   1168: 1234567890
                   1169: 5!a
                   1170: @end example
                   1171: 
                   1172: A frequent beginner's error is to leave away necessary white space,
                   1173: resulting in an error like @samp{Undefined word}; so if you see such an
                   1174: error, check if you have put spaces wherever necessary.
                   1175: 
                   1176: @example
                   1177: ." hello, world" \ correct
                   1178: ."hello, world"  \ gives an "Undefined word" error
                   1179: @end example
                   1180: 
1.65      anton    1181: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1182: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1183: your system is case-sensitive, you may have to type all the examples
                   1184: given here in upper case.
                   1185: 
                   1186: 
                   1187: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1188: @section Crash Course
                   1189: 
                   1190: Type
                   1191: 
                   1192: @example
                   1193: 0 0 !
                   1194: here execute
                   1195: ' catch >body 20 erase abort
                   1196: ' (quit) >body 20 erase
                   1197: @end example
                   1198: 
                   1199: The last two examples are guaranteed to destroy parts of Gforth (and
                   1200: most other systems), so you better leave Gforth afterwards (if it has
                   1201: not finished by itself).  On some systems you may have to kill gforth
                   1202: from outside (e.g., in Unix with @code{kill}).
                   1203: 
                   1204: Now that you know how to produce crashes (and that there's not much to
                   1205: them), let's learn how to produce meaningful programs.
                   1206: 
                   1207: 
                   1208: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1209: @section Stack
1.66      anton    1210: @cindex stack tutorial
1.48      anton    1211: 
                   1212: The most obvious feature of Forth is the stack.  When you type in a
                   1213: number, it is pushed on the stack.  You can display the content of the
                   1214: stack with @code{.s}.
                   1215: 
                   1216: @example
                   1217: 1 2 .s
                   1218: 3 .s
                   1219: @end example
                   1220: 
                   1221: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1222: appear in @code{.s} output as they appeared in the input.
                   1223: 
                   1224: You can print the top of stack element with @code{.}.
                   1225: 
                   1226: @example
                   1227: 1 2 3 . . .
                   1228: @end example
                   1229: 
                   1230: In general, words consume their stack arguments (@code{.s} is an
                   1231: exception).
                   1232: 
                   1233: @assignment
                   1234: What does the stack contain after @code{5 6 7 .}?
                   1235: @endassignment
                   1236: 
                   1237: 
                   1238: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1239: @section Arithmetics
1.66      anton    1240: @cindex arithmetics tutorial
1.48      anton    1241: 
                   1242: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1243: operate on the top two stack items:
                   1244: 
                   1245: @example
1.67      anton    1246: 2 2 .s
                   1247: + .s
                   1248: .
1.48      anton    1249: 2 1 - .
                   1250: 7 3 mod .
                   1251: @end example
                   1252: 
                   1253: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1254: as in the corresponding infix expression (this is generally the case in
                   1255: Forth).
                   1256: 
                   1257: Parentheses are superfluous (and not available), because the order of
                   1258: the words unambiguously determines the order of evaluation and the
                   1259: operands:
                   1260: 
                   1261: @example
                   1262: 3 4 + 5 * .
                   1263: 3 4 5 * + .
                   1264: @end example
                   1265: 
                   1266: @assignment
                   1267: What are the infix expressions corresponding to the Forth code above?
                   1268: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1269: known as Postfix or RPN (Reverse Polish Notation).}.
                   1270: @endassignment
                   1271: 
                   1272: To change the sign, use @code{negate}:
                   1273: 
                   1274: @example
                   1275: 2 negate .
                   1276: @end example
                   1277: 
                   1278: @assignment
                   1279: Convert -(-3)*4-5 to Forth.
                   1280: @endassignment
                   1281: 
                   1282: @code{/mod} performs both @code{/} and @code{mod}.
                   1283: 
                   1284: @example
                   1285: 7 3 /mod . .
                   1286: @end example
                   1287: 
1.66      anton    1288: Reference: @ref{Arithmetic}.
                   1289: 
                   1290: 
1.48      anton    1291: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1292: @section Stack Manipulation
1.66      anton    1293: @cindex stack manipulation tutorial
1.48      anton    1294: 
                   1295: Stack manipulation words rearrange the data on the stack.
                   1296: 
                   1297: @example
                   1298: 1 .s drop .s
                   1299: 1 .s dup .s drop drop .s
                   1300: 1 2 .s over .s drop drop drop
                   1301: 1 2 .s swap .s drop drop
                   1302: 1 2 3 .s rot .s drop drop drop
                   1303: @end example
                   1304: 
                   1305: These are the most important stack manipulation words.  There are also
                   1306: variants that manipulate twice as many stack items:
                   1307: 
                   1308: @example
                   1309: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1310: @end example
                   1311: 
                   1312: Two more stack manipulation words are:
                   1313: 
                   1314: @example
                   1315: 1 2 .s nip .s drop
                   1316: 1 2 .s tuck .s 2drop drop
                   1317: @end example
                   1318: 
                   1319: @assignment
                   1320: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1321: manipulation words.
                   1322: 
                   1323: @example
                   1324: Given:          How do you get:
                   1325: 1 2 3           3 2 1           
                   1326: 1 2 3           1 2 3 2                 
                   1327: 1 2 3           1 2 3 3                 
                   1328: 1 2 3           1 3 3           
                   1329: 1 2 3           2 1 3           
                   1330: 1 2 3 4         4 3 2 1         
                   1331: 1 2 3           1 2 3 1 2 3             
                   1332: 1 2 3 4         1 2 3 4 1 2             
                   1333: 1 2 3
                   1334: 1 2 3           1 2 3 4                 
                   1335: 1 2 3           1 3             
                   1336: @end example
                   1337: @endassignment
                   1338: 
                   1339: @example
                   1340: 5 dup * .
                   1341: @end example
                   1342: 
                   1343: @assignment
                   1344: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1345: Write a piece of Forth code that expects two numbers on the stack
                   1346: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1347: @code{(a-b)(a+1)}.
                   1348: @endassignment
                   1349: 
1.66      anton    1350: Reference: @ref{Stack Manipulation}.
                   1351: 
                   1352: 
1.48      anton    1353: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1354: @section Using files for Forth code
1.66      anton    1355: @cindex loading Forth code, tutorial
                   1356: @cindex files containing Forth code, tutorial
1.48      anton    1357: 
                   1358: While working at the Forth command line is convenient for one-line
                   1359: examples and short one-off code, you probably want to store your source
                   1360: code in files for convenient editing and persistence.  You can use your
                   1361: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102     anton    1362: Gforth}) to create @var{file.fs} and use
1.48      anton    1363: 
                   1364: @example
1.102     anton    1365: s" @var{file.fs}" included
1.48      anton    1366: @end example
                   1367: 
                   1368: to load it into your Forth system.  The file name extension I use for
                   1369: Forth files is @samp{.fs}.
                   1370: 
                   1371: You can easily start Gforth with some files loaded like this:
                   1372: 
                   1373: @example
1.102     anton    1374: gforth @var{file1.fs} @var{file2.fs}
1.48      anton    1375: @end example
                   1376: 
                   1377: If an error occurs during loading these files, Gforth terminates,
                   1378: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1379: a Gforth command line.  Starting the Forth system every time gives you a
                   1380: clean start every time, without interference from the results of earlier
                   1381: tries.
                   1382: 
                   1383: I often put all the tests in a file, then load the code and run the
                   1384: tests with
                   1385: 
                   1386: @example
1.102     anton    1387: gforth @var{code.fs} @var{tests.fs} -e bye
1.48      anton    1388: @end example
                   1389: 
                   1390: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1391: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1392: restart this command without ado.
                   1393: 
                   1394: The advantage of this approach is that the tests can be repeated easily
                   1395: every time the program ist changed, making it easy to catch bugs
                   1396: introduced by the change.
                   1397: 
1.66      anton    1398: Reference: @ref{Forth source files}.
                   1399: 
1.48      anton    1400: 
                   1401: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1402: @section Comments
1.66      anton    1403: @cindex comments tutorial
1.48      anton    1404: 
                   1405: @example
                   1406: \ That's a comment; it ends at the end of the line
                   1407: ( Another comment; it ends here: )  .s
                   1408: @end example
                   1409: 
                   1410: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1411: separated with white space from the following text.
                   1412: 
                   1413: @example
                   1414: \This gives an "Undefined word" error
                   1415: @end example
                   1416: 
                   1417: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1418: nest @code{(}-comments; and you cannot comment out text containing a
                   1419: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1420: avoid @code{)} in word names.}.
                   1421: 
                   1422: I use @code{\}-comments for descriptive text and for commenting out code
                   1423: of one or more line; I use @code{(}-comments for describing the stack
                   1424: effect, the stack contents, or for commenting out sub-line pieces of
                   1425: code.
                   1426: 
                   1427: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1428: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1429: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1430: with @kbd{M-q}.
                   1431: 
1.66      anton    1432: Reference: @ref{Comments}.
                   1433: 
1.48      anton    1434: 
                   1435: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1436: @section Colon Definitions
1.66      anton    1437: @cindex colon definitions, tutorial
                   1438: @cindex definitions, tutorial
                   1439: @cindex procedures, tutorial
                   1440: @cindex functions, tutorial
1.48      anton    1441: 
                   1442: are similar to procedures and functions in other programming languages.
                   1443: 
                   1444: @example
                   1445: : squared ( n -- n^2 )
                   1446:    dup * ;
                   1447: 5 squared .
                   1448: 7 squared .
                   1449: @end example
                   1450: 
                   1451: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1452: following comment describes its stack effect.  The words @code{dup *}
                   1453: are not executed, but compiled into the definition.  @code{;} ends the
                   1454: colon definition.
                   1455: 
                   1456: The newly-defined word can be used like any other word, including using
                   1457: it in other definitions:
                   1458: 
                   1459: @example
                   1460: : cubed ( n -- n^3 )
                   1461:    dup squared * ;
                   1462: -5 cubed .
                   1463: : fourth-power ( n -- n^4 )
                   1464:    squared squared ;
                   1465: 3 fourth-power .
                   1466: @end example
                   1467: 
                   1468: @assignment
                   1469: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1470: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1471: test your tests on the originals first).  Don't let the
                   1472: @samp{redefined}-Messages spook you, they are just warnings.
                   1473: @endassignment
                   1474: 
1.66      anton    1475: Reference: @ref{Colon Definitions}.
                   1476: 
1.48      anton    1477: 
                   1478: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1479: @section Decompilation
1.66      anton    1480: @cindex decompilation tutorial
                   1481: @cindex see tutorial
1.48      anton    1482: 
                   1483: You can decompile colon definitions with @code{see}:
                   1484: 
                   1485: @example
                   1486: see squared
                   1487: see cubed
                   1488: @end example
                   1489: 
                   1490: In Gforth @code{see} shows you a reconstruction of the source code from
                   1491: the executable code.  Informations that were present in the source, but
                   1492: not in the executable code, are lost (e.g., comments).
                   1493: 
1.65      anton    1494: You can also decompile the predefined words:
                   1495: 
                   1496: @example
                   1497: see .
                   1498: see +
                   1499: @end example
                   1500: 
                   1501: 
1.48      anton    1502: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1503: @section Stack-Effect Comments
1.66      anton    1504: @cindex stack-effect comments, tutorial
                   1505: @cindex --, tutorial
1.48      anton    1506: By convention the comment after the name of a definition describes the
                   1507: stack effect: The part in from of the @samp{--} describes the state of
                   1508: the stack before the execution of the definition, i.e., the parameters
                   1509: that are passed into the colon definition; the part behind the @samp{--}
                   1510: is the state of the stack after the execution of the definition, i.e.,
                   1511: the results of the definition.  The stack comment only shows the top
                   1512: stack items that the definition accesses and/or changes.
                   1513: 
                   1514: You should put a correct stack effect on every definition, even if it is
                   1515: just @code{( -- )}.  You should also add some descriptive comment to
                   1516: more complicated words (I usually do this in the lines following
                   1517: @code{:}).  If you don't do this, your code becomes unreadable (because
                   1518: you have to work through every definition before you can undertsand
                   1519: any).
                   1520: 
                   1521: @assignment
                   1522: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1523: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1524: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1525: are done, you can compare your stack effects to those in this manual
1.48      anton    1526: (@pxref{Word Index}).
                   1527: @endassignment
                   1528: 
                   1529: Sometimes programmers put comments at various places in colon
                   1530: definitions that describe the contents of the stack at that place (stack
                   1531: comments); i.e., they are like the first part of a stack-effect
                   1532: comment. E.g.,
                   1533: 
                   1534: @example
                   1535: : cubed ( n -- n^3 )
                   1536:    dup squared  ( n n^2 ) * ;
                   1537: @end example
                   1538: 
                   1539: In this case the stack comment is pretty superfluous, because the word
                   1540: is simple enough.  If you think it would be a good idea to add such a
                   1541: comment to increase readability, you should also consider factoring the
                   1542: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1543: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1544: however, if you decide not to refactor it, then having such a comment is
                   1545: better than not having it.
                   1546: 
                   1547: The names of the stack items in stack-effect and stack comments in the
                   1548: standard, in this manual, and in many programs specify the type through
                   1549: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1550: frequent prefixes are:
                   1551: 
                   1552: @table @code
                   1553: @item n
                   1554: signed integer
                   1555: @item u
                   1556: unsigned integer
                   1557: @item c
                   1558: character
                   1559: @item f
                   1560: Boolean flags, i.e. @code{false} or @code{true}.
                   1561: @item a-addr,a-
                   1562: Cell-aligned address
                   1563: @item c-addr,c-
                   1564: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1565: @item xt
                   1566: Execution token, same size as Cell
                   1567: @item w,x
                   1568: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1569: 16 bits (depending on your platform and Forth system). A cell is more
                   1570: commonly known as machine word, but the term @emph{word} already means
                   1571: something different in Forth.
                   1572: @item d
                   1573: signed double-cell integer
                   1574: @item ud
                   1575: unsigned double-cell integer
                   1576: @item r
                   1577: Float (on the FP stack)
                   1578: @end table
                   1579: 
                   1580: You can find a more complete list in @ref{Notation}.
                   1581: 
                   1582: @assignment
                   1583: Write stack-effect comments for all definitions you have written up to
                   1584: now.
                   1585: @endassignment
                   1586: 
                   1587: 
                   1588: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1589: @section Types
1.66      anton    1590: @cindex types tutorial
1.48      anton    1591: 
                   1592: In Forth the names of the operations are not overloaded; so similar
                   1593: operations on different types need different names; e.g., @code{+} adds
                   1594: integers, and you have to use @code{f+} to add floating-point numbers.
                   1595: The following prefixes are often used for related operations on
                   1596: different types:
                   1597: 
                   1598: @table @code
                   1599: @item (none)
                   1600: signed integer
                   1601: @item u
                   1602: unsigned integer
                   1603: @item c
                   1604: character
                   1605: @item d
                   1606: signed double-cell integer
                   1607: @item ud, du
                   1608: unsigned double-cell integer
                   1609: @item 2
                   1610: two cells (not-necessarily double-cell numbers)
                   1611: @item m, um
                   1612: mixed single-cell and double-cell operations
                   1613: @item f
                   1614: floating-point (note that in stack comments @samp{f} represents flags,
1.66      anton    1615: and @samp{r} represents FP numbers).
1.48      anton    1616: @end table
                   1617: 
                   1618: If there are no differences between the signed and the unsigned variant
                   1619: (e.g., for @code{+}), there is only the prefix-less variant.
                   1620: 
                   1621: Forth does not perform type checking, neither at compile time, nor at
                   1622: run time.  If you use the wrong oeration, the data are interpreted
                   1623: incorrectly:
                   1624: 
                   1625: @example
                   1626: -1 u.
                   1627: @end example
                   1628: 
                   1629: If you have only experience with type-checked languages until now, and
                   1630: have heard how important type-checking is, don't panic!  In my
                   1631: experience (and that of other Forthers), type errors in Forth code are
                   1632: usually easy to find (once you get used to it), the increased vigilance
                   1633: of the programmer tends to catch some harder errors in addition to most
                   1634: type errors, and you never have to work around the type system, so in
                   1635: most situations the lack of type-checking seems to be a win (projects to
                   1636: add type checking to Forth have not caught on).
                   1637: 
                   1638: 
                   1639: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1640: @section Factoring
1.66      anton    1641: @cindex factoring tutorial
1.48      anton    1642: 
                   1643: If you try to write longer definitions, you will soon find it hard to
                   1644: keep track of the stack contents.  Therefore, good Forth programmers
                   1645: tend to write only short definitions (e.g., three lines).  The art of
                   1646: finding meaningful short definitions is known as factoring (as in
                   1647: factoring polynomials).
                   1648: 
                   1649: Well-factored programs offer additional advantages: smaller, more
                   1650: general words, are easier to test and debug and can be reused more and
                   1651: better than larger, specialized words.
                   1652: 
                   1653: So, if you run into difficulties with stack management, when writing
                   1654: code, try to define meaningful factors for the word, and define the word
                   1655: in terms of those.  Even if a factor contains only two words, it is
                   1656: often helpful.
                   1657: 
1.65      anton    1658: Good factoring is not easy, and it takes some practice to get the knack
                   1659: for it; but even experienced Forth programmers often don't find the
                   1660: right solution right away, but only when rewriting the program.  So, if
                   1661: you don't come up with a good solution immediately, keep trying, don't
                   1662: despair.
1.48      anton    1663: 
                   1664: @c example !!
                   1665: 
                   1666: 
                   1667: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1668: @section Designing the stack effect
1.66      anton    1669: @cindex Stack effect design, tutorial
                   1670: @cindex design of stack effects, tutorial
1.48      anton    1671: 
                   1672: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1673: function; and since there is only one result, you don't have to deal with
1.48      anton    1674: the order of results, either.
                   1675: 
                   1676: In Forth (and other stack-based languages, e.g., Postscript) the
                   1677: parameter and result order of a definition is important and should be
                   1678: designed well.  The general guideline is to design the stack effect such
                   1679: that the word is simple to use in most cases, even if that complicates
                   1680: the implementation of the word.  Some concrete rules are:
                   1681: 
                   1682: @itemize @bullet
                   1683: 
                   1684: @item
                   1685: Words consume all of their parameters (e.g., @code{.}).
                   1686: 
                   1687: @item
                   1688: If there is a convention on the order of parameters (e.g., from
                   1689: mathematics or another programming language), stick with it (e.g.,
                   1690: @code{-}).
                   1691: 
                   1692: @item
                   1693: If one parameter usually requires only a short computation (e.g., it is
                   1694: a constant), pass it on the top of the stack.  Conversely, parameters
                   1695: that usually require a long sequence of code to compute should be passed
                   1696: as the bottom (i.e., first) parameter.  This makes the code easier to
                   1697: read, because reader does not need to keep track of the bottom item
                   1698: through a long sequence of code (or, alternatively, through stack
1.49      anton    1699: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    1700: address on top of the stack because it is usually simpler to compute
                   1701: than the stored value (often the address is just a variable).
                   1702: 
                   1703: @item
                   1704: Similarly, results that are usually consumed quickly should be returned
                   1705: on the top of stack, whereas a result that is often used in long
                   1706: computations should be passed as bottom result.  E.g., the file words
                   1707: like @code{open-file} return the error code on the top of stack, because
                   1708: it is usually consumed quickly by @code{throw}; moreover, the error code
                   1709: has to be checked before doing anything with the other results.
                   1710: 
                   1711: @end itemize
                   1712: 
                   1713: These rules are just general guidelines, don't lose sight of the overall
                   1714: goal to make the words easy to use.  E.g., if the convention rule
                   1715: conflicts with the computation-length rule, you might decide in favour
                   1716: of the convention if the word will be used rarely, and in favour of the
                   1717: computation-length rule if the word will be used frequently (because
                   1718: with frequent use the cost of breaking the computation-length rule would
                   1719: be quite high, and frequent use makes it easier to remember an
                   1720: unconventional order).
                   1721: 
                   1722: @c example !! structure package
                   1723: 
1.65      anton    1724: 
1.48      anton    1725: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   1726: @section Local Variables
1.66      anton    1727: @cindex local variables, tutorial
1.48      anton    1728: 
                   1729: You can define local variables (@emph{locals}) in a colon definition:
                   1730: 
                   1731: @example
                   1732: : swap @{ a b -- b a @}
                   1733:   b a ;
                   1734: 1 2 swap .s 2drop
                   1735: @end example
                   1736: 
                   1737: (If your Forth system does not support this syntax, include
                   1738: @file{compat/anslocals.fs} first).
                   1739: 
                   1740: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   1741: takes two cells from the stack, puts the top of stack in @code{b} and
                   1742: the next stack element in @code{a}.  @code{--} starts a comment ending
                   1743: with @code{@}}.  After the locals definition, using the name of the
                   1744: local will push its value on the stack.  You can leave the comment
                   1745: part (@code{-- b a}) away:
                   1746: 
                   1747: @example
                   1748: : swap ( x1 x2 -- x2 x1 )
                   1749:   @{ a b @} b a ;
                   1750: @end example
                   1751: 
                   1752: In Gforth you can have several locals definitions, anywhere in a colon
                   1753: definition; in contrast, in a standard program you can have only one
                   1754: locals definition per colon definition, and that locals definition must
                   1755: be outside any controll structure.
                   1756: 
                   1757: With locals you can write slightly longer definitions without running
                   1758: into stack trouble.  However, I recommend trying to write colon
                   1759: definitions without locals for exercise purposes to help you gain the
                   1760: essential factoring skills.
                   1761: 
                   1762: @assignment
                   1763: Rewrite your definitions until now with locals
                   1764: @endassignment
                   1765: 
1.66      anton    1766: Reference: @ref{Locals}.
                   1767: 
1.48      anton    1768: 
                   1769: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   1770: @section Conditional execution
1.66      anton    1771: @cindex conditionals, tutorial
                   1772: @cindex if, tutorial
1.48      anton    1773: 
                   1774: In Forth you can use control structures only inside colon definitions.
                   1775: An @code{if}-structure looks like this:
                   1776: 
                   1777: @example
                   1778: : abs ( n1 -- +n2 )
                   1779:     dup 0 < if
                   1780:         negate
                   1781:     endif ;
                   1782: 5 abs .
                   1783: -5 abs .
                   1784: @end example
                   1785: 
                   1786: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   1787: the following code is performed, otherwise execution continues after the
1.51      pazsan   1788: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.48      anton    1789: elements and prioduces a flag:
                   1790: 
                   1791: @example
                   1792: 1 2 < .
                   1793: 2 1 < .
                   1794: 1 1 < .
                   1795: @end example
                   1796: 
                   1797: Actually the standard name for @code{endif} is @code{then}.  This
                   1798: tutorial presents the examples using @code{endif}, because this is often
                   1799: less confusing for people familiar with other programming languages
                   1800: where @code{then} has a different meaning.  If your system does not have
                   1801: @code{endif}, define it with
                   1802: 
                   1803: @example
                   1804: : endif postpone then ; immediate
                   1805: @end example
                   1806: 
                   1807: You can optionally use an @code{else}-part:
                   1808: 
                   1809: @example
                   1810: : min ( n1 n2 -- n )
                   1811:   2dup < if
                   1812:     drop
                   1813:   else
                   1814:     nip
                   1815:   endif ;
                   1816: 2 3 min .
                   1817: 3 2 min .
                   1818: @end example
                   1819: 
                   1820: @assignment
                   1821: Write @code{min} without @code{else}-part (hint: what's the definition
                   1822: of @code{nip}?).
                   1823: @endassignment
                   1824: 
1.66      anton    1825: Reference: @ref{Selection}.
                   1826: 
1.48      anton    1827: 
                   1828: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   1829: @section Flags and Comparisons
1.66      anton    1830: @cindex flags tutorial
                   1831: @cindex comparison tutorial
1.48      anton    1832: 
                   1833: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   1834: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   1835: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   1836: treated as true flag.
                   1837: 
                   1838: @example
                   1839: false .
                   1840: true .
                   1841: true hex u. decimal
                   1842: @end example
                   1843: 
                   1844: Comparison words produce canonical flags:
                   1845: 
                   1846: @example
                   1847: 1 1 = .
                   1848: 1 0= .
                   1849: 0 1 < .
                   1850: 0 0 < .
                   1851: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   1852: -1 1 < .
                   1853: @end example
                   1854: 
1.66      anton    1855: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   1856: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   1857: these combinations are standard (for details see the standard,
                   1858: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    1859: 
                   1860: You can use @code{and or xor invert} can be used as operations on
                   1861: canonical flags.  Actually they are bitwise operations:
                   1862: 
                   1863: @example
                   1864: 1 2 and .
                   1865: 1 2 or .
                   1866: 1 3 xor .
                   1867: 1 invert .
                   1868: @end example
                   1869: 
                   1870: You can convert a zero/non-zero flag into a canonical flag with
                   1871: @code{0<>} (and complement it on the way with @code{0=}).
                   1872: 
                   1873: @example
                   1874: 1 0= .
                   1875: 1 0<> .
                   1876: @end example
                   1877: 
1.65      anton    1878: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    1879: operation of the Boolean operations to avoid @code{if}s:
                   1880: 
                   1881: @example
                   1882: : foo ( n1 -- n2 )
                   1883:   0= if
                   1884:     14
                   1885:   else
                   1886:     0
                   1887:   endif ;
                   1888: 0 foo .
                   1889: 1 foo .
                   1890: 
                   1891: : foo ( n1 -- n2 )
                   1892:   0= 14 and ;
                   1893: 0 foo .
                   1894: 1 foo .
                   1895: @end example
                   1896: 
                   1897: @assignment
                   1898: Write @code{min} without @code{if}.
                   1899: @endassignment
                   1900: 
1.66      anton    1901: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   1902: @ref{Bitwise operations}.
                   1903: 
1.48      anton    1904: 
                   1905: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   1906: @section General Loops
1.66      anton    1907: @cindex loops, indefinite, tutorial
1.48      anton    1908: 
                   1909: The endless loop is the most simple one:
                   1910: 
                   1911: @example
                   1912: : endless ( -- )
                   1913:   0 begin
                   1914:     dup . 1+
                   1915:   again ;
                   1916: endless
                   1917: @end example
                   1918: 
                   1919: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   1920: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   1921: 
                   1922: A loop with one exit at any place looks like this:
                   1923: 
                   1924: @example
                   1925: : log2 ( +n1 -- n2 )
                   1926: \ logarithmus dualis of n1>0, rounded down to the next integer
                   1927:   assert( dup 0> )
                   1928:   2/ 0 begin
                   1929:     over 0> while
                   1930:       1+ swap 2/ swap
                   1931:   repeat
                   1932:   nip ;
                   1933: 7 log2 .
                   1934: 8 log2 .
                   1935: @end example
                   1936: 
                   1937: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   1938: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    1939: continues behind the @code{while}.  @code{Repeat} jumps back to
                   1940: @code{begin}, just like @code{again}.
                   1941: 
                   1942: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90      anton    1943: However, @code{2/} is not one of them; it shifts its argument right by
1.48      anton    1944: one bit (arithmetic shift right):
                   1945: 
                   1946: @example
                   1947: -5 2 / .
                   1948: -5 2/ .
                   1949: @end example
                   1950: 
                   1951: @code{assert(} is no standard word, but you can get it on systems other
                   1952: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   1953: does by trying
                   1954: 
                   1955: @example
                   1956: 0 log2 .
                   1957: @end example
                   1958: 
                   1959: Here's a loop with an exit at the end:
                   1960: 
                   1961: @example
                   1962: : log2 ( +n1 -- n2 )
                   1963: \ logarithmus dualis of n1>0, rounded down to the next integer
                   1964:   assert( dup 0 > )
                   1965:   -1 begin
                   1966:     1+ swap 2/ swap
                   1967:     over 0 <=
                   1968:   until
                   1969:   nip ;
                   1970: @end example
                   1971: 
                   1972: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   1973: the @code{begin}, otherwise after the @code{until}.
                   1974: 
                   1975: @assignment
                   1976: Write a definition for computing the greatest common divisor.
                   1977: @endassignment
                   1978: 
1.66      anton    1979: Reference: @ref{Simple Loops}.
                   1980: 
1.48      anton    1981: 
                   1982: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   1983: @section Counted loops
1.66      anton    1984: @cindex loops, counted, tutorial
1.48      anton    1985: 
                   1986: @example
                   1987: : ^ ( n1 u -- n )
                   1988: \ n = the uth power of u1
                   1989:   1 swap 0 u+do
                   1990:     over *
                   1991:   loop
                   1992:   nip ;
                   1993: 3 2 ^ .
                   1994: 4 3 ^ .
                   1995: @end example
                   1996: 
                   1997: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   1998: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   1999: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2000: times (or not at all, if @code{u3-u4<0}).
                   2001: 
                   2002: You can see the stack effect design rules at work in the stack effect of
                   2003: the loop start words: Since the start value of the loop is more
                   2004: frequently constant than the end value, the start value is passed on
                   2005: the top-of-stack.
                   2006: 
                   2007: You can access the counter of a counted loop with @code{i}:
                   2008: 
                   2009: @example
                   2010: : fac ( u -- u! )
                   2011:   1 swap 1+ 1 u+do
                   2012:     i *
                   2013:   loop ;
                   2014: 5 fac .
                   2015: 7 fac .
                   2016: @end example
                   2017: 
                   2018: There is also @code{+do}, which expects signed numbers (important for
                   2019: deciding whether to enter the loop).
                   2020: 
                   2021: @assignment
                   2022: Write a definition for computing the nth Fibonacci number.
                   2023: @endassignment
                   2024: 
1.65      anton    2025: You can also use increments other than 1:
                   2026: 
                   2027: @example
                   2028: : up2 ( n1 n2 -- )
                   2029:   +do
                   2030:     i .
                   2031:   2 +loop ;
                   2032: 10 0 up2
                   2033: 
                   2034: : down2 ( n1 n2 -- )
                   2035:   -do
                   2036:     i .
                   2037:   2 -loop ;
                   2038: 0 10 down2
                   2039: @end example
1.48      anton    2040: 
1.66      anton    2041: Reference: @ref{Counted Loops}.
                   2042: 
1.48      anton    2043: 
                   2044: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2045: @section Recursion
1.66      anton    2046: @cindex recursion tutorial
1.48      anton    2047: 
                   2048: Usually the name of a definition is not visible in the definition; but
                   2049: earlier definitions are usually visible:
                   2050: 
                   2051: @example
                   2052: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
                   2053: : / ( n1 n2 -- n )
                   2054:   dup 0= if
                   2055:     -10 throw \ report division by zero
                   2056:   endif
                   2057:   /           \ old version
                   2058: ;
                   2059: 1 0 /
                   2060: @end example
                   2061: 
                   2062: For recursive definitions you can use @code{recursive} (non-standard) or
                   2063: @code{recurse}:
                   2064: 
                   2065: @example
                   2066: : fac1 ( n -- n! ) recursive
                   2067:  dup 0> if
                   2068:    dup 1- fac1 *
                   2069:  else
                   2070:    drop 1
                   2071:  endif ;
                   2072: 7 fac1 .
                   2073: 
                   2074: : fac2 ( n -- n! )
                   2075:  dup 0> if
                   2076:    dup 1- recurse *
                   2077:  else
                   2078:    drop 1
                   2079:  endif ;
                   2080: 8 fac2 .
                   2081: @end example
                   2082: 
                   2083: @assignment
                   2084: Write a recursive definition for computing the nth Fibonacci number.
                   2085: @endassignment
                   2086: 
1.66      anton    2087: Reference (including indirect recursion): @xref{Calls and returns}.
                   2088: 
1.48      anton    2089: 
                   2090: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2091: @section Leaving definitions or loops
1.66      anton    2092: @cindex leaving definitions, tutorial
                   2093: @cindex leaving loops, tutorial
1.48      anton    2094: 
                   2095: @code{EXIT} exits the current definition right away.  For every counted
                   2096: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2097: before the @code{EXIT}:
                   2098: 
                   2099: @c !! real examples
                   2100: @example
                   2101: : ...
                   2102:  ... u+do
                   2103:    ... if
                   2104:      ... unloop exit
                   2105:    endif
                   2106:    ...
                   2107:  loop
                   2108:  ... ;
                   2109: @end example
                   2110: 
                   2111: @code{LEAVE} leaves the innermost counted loop right away:
                   2112: 
                   2113: @example
                   2114: : ...
                   2115:  ... u+do
                   2116:    ... if
                   2117:      ... leave
                   2118:    endif
                   2119:    ...
                   2120:  loop
                   2121:  ... ;
                   2122: @end example
                   2123: 
1.65      anton    2124: @c !! example
1.48      anton    2125: 
1.66      anton    2126: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2127: 
                   2128: 
1.48      anton    2129: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2130: @section Return Stack
1.66      anton    2131: @cindex return stack tutorial
1.48      anton    2132: 
                   2133: In addition to the data stack Forth also has a second stack, the return
                   2134: stack; most Forth systems store the return addresses of procedure calls
                   2135: there (thus its name).  Programmers can also use this stack:
                   2136: 
                   2137: @example
                   2138: : foo ( n1 n2 -- )
                   2139:  .s
                   2140:  >r .s
1.50      anton    2141:  r@@ .
1.48      anton    2142:  >r .s
1.50      anton    2143:  r@@ .
1.48      anton    2144:  r> .
1.50      anton    2145:  r@@ .
1.48      anton    2146:  r> . ;
                   2147: 1 2 foo
                   2148: @end example
                   2149: 
                   2150: @code{>r} takes an element from the data stack and pushes it onto the
                   2151: return stack; conversely, @code{r>} moves an elementm from the return to
                   2152: the data stack; @code{r@@} pushes a copy of the top of the return stack
                   2153: on the return stack.
                   2154: 
                   2155: Forth programmers usually use the return stack for storing data
                   2156: temporarily, if using the data stack alone would be too complex, and
                   2157: factoring and locals are not an option:
                   2158: 
                   2159: @example
                   2160: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2161:  rot >r rot r> ;
                   2162: @end example
                   2163: 
                   2164: The return address of the definition and the loop control parameters of
                   2165: counted loops usually reside on the return stack, so you have to take
                   2166: all items, that you have pushed on the return stack in a colon
                   2167: definition or counted loop, from the return stack before the definition
                   2168: or loop ends.  You cannot access items that you pushed on the return
                   2169: stack outside some definition or loop within the definition of loop.
                   2170: 
                   2171: If you miscount the return stack items, this usually ends in a crash:
                   2172: 
                   2173: @example
                   2174: : crash ( n -- )
                   2175:   >r ;
                   2176: 5 crash
                   2177: @end example
                   2178: 
                   2179: You cannot mix using locals and using the return stack (according to the
                   2180: standard; Gforth has no problem).  However, they solve the same
                   2181: problems, so this shouldn't be an issue.
                   2182: 
                   2183: @assignment
                   2184: Can you rewrite any of the definitions you wrote until now in a better
                   2185: way using the return stack?
                   2186: @endassignment
                   2187: 
1.66      anton    2188: Reference: @ref{Return stack}.
                   2189: 
1.48      anton    2190: 
                   2191: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2192: @section Memory
1.66      anton    2193: @cindex memory access/allocation tutorial
1.48      anton    2194: 
                   2195: You can create a global variable @code{v} with
                   2196: 
                   2197: @example
                   2198: variable v ( -- addr )
                   2199: @end example
                   2200: 
                   2201: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2202: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2203: values into this cell and @code{@@} (fetch) to load the value from the
                   2204: stack into memory:
                   2205: 
                   2206: @example
                   2207: v .
                   2208: 5 v ! .s
1.50      anton    2209: v @@ .
1.48      anton    2210: @end example
                   2211: 
1.65      anton    2212: You can see a raw dump of memory with @code{dump}:
                   2213: 
                   2214: @example
                   2215: v 1 cells .s dump
                   2216: @end example
                   2217: 
                   2218: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2219: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2220: also reserve more memory:
1.48      anton    2221: 
                   2222: @example
                   2223: create v2 20 cells allot
1.65      anton    2224: v2 20 cells dump
1.48      anton    2225: @end example
                   2226: 
1.65      anton    2227: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2228: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2229: can use address arithmetic to access these cells:
1.48      anton    2230: 
                   2231: @example
                   2232: 3 v2 5 cells + !
1.65      anton    2233: v2 20 cells dump
1.48      anton    2234: @end example
                   2235: 
                   2236: You can reserve and initialize memory with @code{,}:
                   2237: 
                   2238: @example
                   2239: create v3
                   2240:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2241: v3 @@ .
                   2242: v3 cell+ @@ .
                   2243: v3 2 cells + @@ .
1.65      anton    2244: v3 5 cells dump
1.48      anton    2245: @end example
                   2246: 
                   2247: @assignment
                   2248: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2249: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2250: one at @code{addr cell+} etc.
                   2251: @endassignment
                   2252: 
                   2253: You can also reserve memory without creating a new word:
                   2254: 
                   2255: @example
1.60      anton    2256: here 10 cells allot .
                   2257: here .
1.48      anton    2258: @end example
                   2259: 
                   2260: @code{Here} pushes the start address of the memory area.  You should
                   2261: store it somewhere, or you will have a hard time finding the memory area
                   2262: again.
                   2263: 
                   2264: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2265: the system's data structures for words etc. on Gforth and most other
                   2266: Forth systems.  It is managed like a stack: You can free the memory that
                   2267: you have just @code{allot}ed with
                   2268: 
                   2269: @example
                   2270: -10 cells allot
1.60      anton    2271: here .
1.48      anton    2272: @end example
                   2273: 
                   2274: Note that you cannot do this if you have created a new word in the
                   2275: meantime (because then your @code{allot}ed memory is no longer on the
                   2276: top of the dictionary ``stack'').
                   2277: 
                   2278: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2279: freeing memory in any order:
                   2280: 
                   2281: @example
                   2282: 10 cells allocate throw .s
                   2283: 20 cells allocate throw .s
                   2284: swap
                   2285: free throw
                   2286: free throw
                   2287: @end example
                   2288: 
                   2289: The @code{throw}s deal with errors (e.g., out of memory).
                   2290: 
1.65      anton    2291: And there is also a
                   2292: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2293: garbage collector}, which eliminates the need to @code{free} memory
                   2294: explicitly.
1.48      anton    2295: 
1.66      anton    2296: Reference: @ref{Memory}.
                   2297: 
1.48      anton    2298: 
                   2299: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2300: @section Characters and Strings
1.66      anton    2301: @cindex strings tutorial
                   2302: @cindex characters tutorial
1.48      anton    2303: 
                   2304: On the stack characters take up a cell, like numbers.  In memory they
                   2305: have their own size (one 8-bit byte on most systems), and therefore
                   2306: require their own words for memory access:
                   2307: 
                   2308: @example
                   2309: create v4 
                   2310:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2311: v4 4 chars + c@@ .
1.65      anton    2312: v4 5 chars dump
1.48      anton    2313: @end example
                   2314: 
                   2315: The preferred representation of strings on the stack is @code{addr
                   2316: u-count}, where @code{addr} is the address of the first character and
                   2317: @code{u-count} is the number of characters in the string.
                   2318: 
                   2319: @example
                   2320: v4 5 type
                   2321: @end example
                   2322: 
                   2323: You get a string constant with
                   2324: 
                   2325: @example
                   2326: s" hello, world" .s
                   2327: type
                   2328: @end example
                   2329: 
                   2330: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2331: is a normal Forth word and must be delimited with white space (try what
                   2332: happens when you remove the space).
                   2333: 
                   2334: However, this interpretive use of @code{s"} is quite restricted: the
                   2335: string exists only until the next call of @code{s"} (some Forth systems
                   2336: keep more than one of these strings, but usually they still have a
1.62      crook    2337: limited lifetime).
1.48      anton    2338: 
                   2339: @example
                   2340: s" hello," s" world" .s
                   2341: type
                   2342: type
                   2343: @end example
                   2344: 
1.62      crook    2345: You can also use @code{s"} in a definition, and the resulting
                   2346: strings then live forever (well, for as long as the definition):
1.48      anton    2347: 
                   2348: @example
                   2349: : foo s" hello," s" world" ;
                   2350: foo .s
                   2351: type
                   2352: type
                   2353: @end example
                   2354: 
                   2355: @assignment
                   2356: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2357: Implement @code{type ( addr u -- )}.
                   2358: @endassignment
                   2359: 
1.66      anton    2360: Reference: @ref{Memory Blocks}.
                   2361: 
                   2362: 
1.84      pazsan   2363: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2364: @section Alignment
1.66      anton    2365: @cindex alignment tutorial
                   2366: @cindex memory alignment tutorial
1.48      anton    2367: 
                   2368: On many processors cells have to be aligned in memory, if you want to
                   2369: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2370: not require alignment, access to aligned cells is faster).
1.48      anton    2371: 
                   2372: @code{Create} aligns @code{here} (i.e., the place where the next
                   2373: allocation will occur, and that the @code{create}d word points to).
                   2374: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2375: address.  Adding a number of @code{cells} to an aligned address produces
                   2376: another aligned address.
                   2377: 
                   2378: However, address arithmetic involving @code{char+} and @code{chars} can
                   2379: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2380: a-addr )} produces the next aligned address:
                   2381: 
                   2382: @example
1.50      anton    2383: v3 char+ aligned .s @@ .
                   2384: v3 char+ .s @@ .
1.48      anton    2385: @end example
                   2386: 
                   2387: Similarly, @code{align} advances @code{here} to the next aligned
                   2388: address:
                   2389: 
                   2390: @example
                   2391: create v5 97 c,
                   2392: here .
                   2393: align here .
                   2394: 1000 ,
                   2395: @end example
                   2396: 
                   2397: Note that you should use aligned addresses even if your processor does
                   2398: not require them, if you want your program to be portable.
                   2399: 
1.66      anton    2400: Reference: @ref{Address arithmetic}.
                   2401: 
1.48      anton    2402: 
1.84      pazsan   2403: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
                   2404: @section Files
                   2405: @cindex files tutorial
                   2406: 
                   2407: This section gives a short introduction into how to use files inside
                   2408: Forth. It's broken up into five easy steps:
                   2409: 
                   2410: @enumerate 1
                   2411: @item Opened an ASCII text file for input
                   2412: @item Opened a file for output
                   2413: @item Read input file until string matched (or some other condition matched)
                   2414: @item Wrote some lines from input ( modified or not) to output
                   2415: @item Closed the files.
                   2416: @end enumerate
                   2417: 
                   2418: @subsection Open file for input
                   2419: 
                   2420: @example
                   2421: s" foo.in"  r/o open-file throw Value fd-in
                   2422: @end example
                   2423: 
                   2424: @subsection Create file for output
                   2425: 
                   2426: @example
                   2427: s" foo.out" w/o create-file throw Value fd-out
                   2428: @end example
                   2429: 
                   2430: The available file modes are r/o for read-only access, r/w for
                   2431: read-write access, and w/o for write-only access. You could open both
                   2432: files with r/w, too, if you like. All file words return error codes; for
                   2433: most applications, it's best to pass there error codes with @code{throw}
                   2434: to the outer error handler.
                   2435: 
                   2436: If you want words for opening and assigning, define them as follows:
                   2437: 
                   2438: @example
                   2439: 0 Value fd-in
                   2440: 0 Value fd-out
                   2441: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2442: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2443: @end example
                   2444: 
                   2445: Usage example:
                   2446: 
                   2447: @example
                   2448: s" foo.in" open-input
                   2449: s" foo.out" open-output
                   2450: @end example
                   2451: 
                   2452: @subsection Scan file for a particular line
                   2453: 
                   2454: @example
                   2455: 256 Constant max-line
                   2456: Create line-buffer  max-line 2 + allot
                   2457: 
                   2458: : scan-file ( addr u -- )
                   2459:   begin
                   2460:       line-buffer max-line fd-in read-line throw
                   2461:   while
                   2462:          >r 2dup line-buffer r> compare 0=
                   2463:      until
                   2464:   else
                   2465:      drop
                   2466:   then
                   2467:   2drop ;
                   2468: @end example
                   2469: 
                   2470: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94      anton    2471: the buffer at addr, and returns the number of bytes read, a flag that is
                   2472: false when the end of file is reached, and an error code.
1.84      pazsan   2473: 
                   2474: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2475: returns zero if both strings are equal. It returns a positive number if
                   2476: the first string is lexically greater, a negative if the second string
                   2477: is lexically greater.
                   2478: 
                   2479: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2480: exits with the number of bytes read on the stack, we have to clean up
                   2481: that separately; that's after the @code{else}.
                   2482: 
                   2483: Usage example:
                   2484: 
                   2485: @example
                   2486: s" The text I search is here" scan-file
                   2487: @end example
                   2488: 
                   2489: @subsection Copy input to output
                   2490: 
                   2491: @example
                   2492: : copy-file ( -- )
                   2493:   begin
                   2494:       line-buffer max-line fd-in read-line throw
                   2495:   while
                   2496:       line-buffer swap fd-out write-file throw
                   2497:   repeat ;
                   2498: @end example
                   2499: 
                   2500: @subsection Close files
                   2501: 
                   2502: @example
                   2503: fd-in close-file throw
                   2504: fd-out close-file throw
                   2505: @end example
                   2506: 
                   2507: Likewise, you can put that into definitions, too:
                   2508: 
                   2509: @example
                   2510: : close-input ( -- )  fd-in close-file throw ;
                   2511: : close-output ( -- )  fd-out close-file throw ;
                   2512: @end example
                   2513: 
                   2514: @assignment
                   2515: How could you modify @code{copy-file} so that it copies until a second line is
                   2516: matched? Can you write a program that extracts a section of a text file,
                   2517: given the line that starts and the line that terminates that section?
                   2518: @endassignment
                   2519: 
                   2520: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2521: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2522: @cindex semantics tutorial
                   2523: @cindex interpretation semantics tutorial
                   2524: @cindex compilation semantics tutorial
                   2525: @cindex immediate, tutorial
1.48      anton    2526: 
                   2527: When a word is compiled, it behaves differently from being interpreted.
                   2528: E.g., consider @code{+}:
                   2529: 
                   2530: @example
                   2531: 1 2 + .
                   2532: : foo + ;
                   2533: @end example
                   2534: 
                   2535: These two behaviours are known as compilation and interpretation
                   2536: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2537: is to append the interpretation semantics to the currently defined word
                   2538: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2539: later, the interpretation semantics of @code{+} (i.e., adding two
                   2540: numbers) will be performed.
                   2541: 
                   2542: However, there are words with non-default compilation semantics, e.g.,
                   2543: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2544: change the compilation semantics of the last defined word to be equal to
                   2545: the interpretation semantics:
                   2546: 
                   2547: @example
                   2548: : [FOO] ( -- )
                   2549:  5 . ; immediate
                   2550: 
                   2551: [FOO]
                   2552: : bar ( -- )
                   2553:   [FOO] ;
                   2554: bar
                   2555: see bar
                   2556: @end example
                   2557: 
                   2558: Two conventions to mark words with non-default compilation semnatics are
                   2559: names with brackets (more frequently used) and to write them all in
                   2560: upper case (less frequently used).
                   2561: 
                   2562: In Gforth (and many other systems) you can also remove the
                   2563: interpretation semantics with @code{compile-only} (the compilation
                   2564: semantics is derived from the original interpretation semantics):
                   2565: 
                   2566: @example
                   2567: : flip ( -- )
                   2568:  6 . ; compile-only \ but not immediate
                   2569: flip
                   2570: 
                   2571: : flop ( -- )
                   2572:  flip ;
                   2573: flop
                   2574: @end example
                   2575: 
                   2576: In this example the interpretation semantics of @code{flop} is equal to
                   2577: the original interpretation semantics of @code{flip}.
                   2578: 
                   2579: The text interpreter has two states: in interpret state, it performs the
                   2580: interpretation semantics of words it encounters; in compile state, it
                   2581: performs the compilation semantics of these words.
                   2582: 
                   2583: Among other things, @code{:} switches into compile state, and @code{;}
                   2584: switches back to interpret state.  They contain the factors @code{]}
                   2585: (switch to compile state) and @code{[} (switch to interpret state), that
                   2586: do nothing but switch the state.
                   2587: 
                   2588: @example
                   2589: : xxx ( -- )
                   2590:   [ 5 . ]
                   2591: ;
                   2592: 
                   2593: xxx
                   2594: see xxx
                   2595: @end example
                   2596: 
                   2597: These brackets are also the source of the naming convention mentioned
                   2598: above.
                   2599: 
1.66      anton    2600: Reference: @ref{Interpretation and Compilation Semantics}.
                   2601: 
1.48      anton    2602: 
                   2603: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2604: @section Execution Tokens
1.66      anton    2605: @cindex execution tokens tutorial
                   2606: @cindex XT tutorial
1.48      anton    2607: 
                   2608: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2609: cell representing the interpretation semantics of a word.  You can
                   2610: execute this semantics with @code{execute}:
                   2611: 
                   2612: @example
                   2613: ' + .s
                   2614: 1 2 rot execute .
                   2615: @end example
                   2616: 
                   2617: The XT is similar to a function pointer in C.  However, parameter
                   2618: passing through the stack makes it a little more flexible:
                   2619: 
                   2620: @example
                   2621: : map-array ( ... addr u xt -- ... )
1.50      anton    2622: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2623: \ at addr and containing u elements
1.48      anton    2624:   @{ xt @}
                   2625:   cells over + swap ?do
1.50      anton    2626:     i @@ xt execute
1.48      anton    2627:   1 cells +loop ;
                   2628: 
                   2629: create a 3 , 4 , 2 , -1 , 4 ,
                   2630: a 5 ' . map-array .s
                   2631: 0 a 5 ' + map-array .
                   2632: s" max-n" environment? drop .s
                   2633: a 5 ' min map-array .
                   2634: @end example
                   2635: 
                   2636: You can use map-array with the XTs of words that consume one element
                   2637: more than they produce.  In theory you can also use it with other XTs,
                   2638: but the stack effect then depends on the size of the array, which is
                   2639: hard to understand.
                   2640: 
1.51      pazsan   2641: Since XTs are cell-sized, you can store them in memory and manipulate
                   2642: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2643: word with @code{compile,}:
                   2644: 
                   2645: @example
                   2646: : foo1 ( n1 n2 -- n )
                   2647:    [ ' + compile, ] ;
                   2648: see foo
                   2649: @end example
                   2650: 
                   2651: This is non-standard, because @code{compile,} has no compilation
                   2652: semantics in the standard, but it works in good Forth systems.  For the
                   2653: broken ones, use
                   2654: 
                   2655: @example
                   2656: : [compile,] compile, ; immediate
                   2657: 
                   2658: : foo1 ( n1 n2 -- n )
                   2659:    [ ' + ] [compile,] ;
                   2660: see foo
                   2661: @end example
                   2662: 
                   2663: @code{'} is a word with default compilation semantics; it parses the
                   2664: next word when its interpretation semantics are executed, not during
                   2665: compilation:
                   2666: 
                   2667: @example
                   2668: : foo ( -- xt )
                   2669:   ' ;
                   2670: see foo
                   2671: : bar ( ... "word" -- ... )
                   2672:   ' execute ;
                   2673: see bar
1.60      anton    2674: 1 2 bar + .
1.48      anton    2675: @end example
                   2676: 
                   2677: You often want to parse a word during compilation and compile its XT so
                   2678: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2679: 
                   2680: @example
                   2681: : xt-+ ( -- xt )
                   2682:   ['] + ;
                   2683: see xt-+
                   2684: 1 2 xt-+ execute .
                   2685: @end example
                   2686: 
                   2687: Many programmers tend to see @code{'} and the word it parses as one
                   2688: unit, and expect it to behave like @code{[']} when compiled, and are
                   2689: confused by the actual behaviour.  If you are, just remember that the
                   2690: Forth system just takes @code{'} as one unit and has no idea that it is
                   2691: a parsing word (attempts to convenience programmers in this issue have
                   2692: usually resulted in even worse pitfalls, see
1.66      anton    2693: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2694: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2695: 
                   2696: Note that the state of the interpreter does not come into play when
1.51      pazsan   2697: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2698: compile state, it still gives you the interpretation semantics.  And
                   2699: whatever that state is, @code{execute} performs the semantics
1.66      anton    2700: represented by the XT (i.e., for XTs produced with @code{'} the
                   2701: interpretation semantics).
                   2702: 
                   2703: Reference: @ref{Tokens for Words}.
1.48      anton    2704: 
                   2705: 
                   2706: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2707: @section Exceptions
1.66      anton    2708: @cindex exceptions tutorial
1.48      anton    2709: 
                   2710: @code{throw ( n -- )} causes an exception unless n is zero.
                   2711: 
                   2712: @example
                   2713: 100 throw .s
                   2714: 0 throw .s
                   2715: @end example
                   2716: 
                   2717: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2718: it catches exceptions and pushes the number of the exception on the
                   2719: stack (or 0, if the xt executed without exception).  If there was an
                   2720: exception, the stacks have the same depth as when entering @code{catch}:
                   2721: 
                   2722: @example
                   2723: .s
                   2724: 3 0 ' / catch .s
                   2725: 3 2 ' / catch .s
                   2726: @end example
                   2727: 
                   2728: @assignment
                   2729: Try the same with @code{execute} instead of @code{catch}.
                   2730: @endassignment
                   2731: 
                   2732: @code{Throw} always jumps to the dynamically next enclosing
                   2733: @code{catch}, even if it has to leave several call levels to achieve
                   2734: this:
                   2735: 
                   2736: @example
                   2737: : foo 100 throw ;
                   2738: : foo1 foo ." after foo" ;
1.51      pazsan   2739: : bar ['] foo1 catch ;
1.60      anton    2740: bar .
1.48      anton    2741: @end example
                   2742: 
                   2743: It is often important to restore a value upon leaving a definition, even
                   2744: if the definition is left through an exception.  You can ensure this
                   2745: like this:
                   2746: 
                   2747: @example
                   2748: : ...
                   2749:    save-x
1.51      pazsan   2750:    ['] word-changing-x catch ( ... n )
1.48      anton    2751:    restore-x
                   2752:    ( ... n ) throw ;
                   2753: @end example
                   2754: 
1.55      anton    2755: Gforth provides an alternative syntax in addition to @code{catch}:
1.48      anton    2756: @code{try ... recover ... endtry}.  If the code between @code{try} and
                   2757: @code{recover} has an exception, the stack depths are restored, the
                   2758: exception number is pushed on the stack, and the code between
                   2759: @code{recover} and @code{endtry} is performed.  E.g., the definition for
                   2760: @code{catch} is
                   2761: 
                   2762: @example
                   2763: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
                   2764:   try
                   2765:     execute 0
                   2766:   recover
                   2767:     nip
                   2768:   endtry ;
                   2769: @end example
                   2770: 
                   2771: The equivalent to the restoration code above is
                   2772: 
                   2773: @example
                   2774: : ...
                   2775:   save-x
                   2776:   try
1.92      anton    2777:     word-changing-x 0
                   2778:   recover endtry
1.48      anton    2779:   restore-x
                   2780:   throw ;
                   2781: @end example
                   2782: 
1.92      anton    2783: This works if @code{word-changing-x} does not change the stack depth,
                   2784: otherwise you should add some code between @code{recover} and
                   2785: @code{endtry} to balance the stack.
1.48      anton    2786: 
1.66      anton    2787: Reference: @ref{Exception Handling}.
                   2788: 
1.48      anton    2789: 
                   2790: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   2791: @section Defining Words
1.66      anton    2792: @cindex defining words tutorial
                   2793: @cindex does> tutorial
                   2794: @cindex create...does> tutorial
                   2795: 
                   2796: @c before semantics?
1.48      anton    2797: 
                   2798: @code{:}, @code{create}, and @code{variable} are definition words: They
                   2799: define other words.  @code{Constant} is another definition word:
                   2800: 
                   2801: @example
                   2802: 5 constant foo
                   2803: foo .
                   2804: @end example
                   2805: 
                   2806: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   2807: (floating point) with @code{variable} and @code{constant}.
                   2808: 
                   2809: You can also define your own defining words.  E.g.:
                   2810: 
                   2811: @example
                   2812: : variable ( "name" -- )
                   2813:   create 0 , ;
                   2814: @end example
                   2815: 
                   2816: You can also define defining words that create words that do something
                   2817: other than just producing their address:
                   2818: 
                   2819: @example
                   2820: : constant ( n "name" -- )
                   2821:   create ,
                   2822: does> ( -- n )
1.50      anton    2823:   ( addr ) @@ ;
1.48      anton    2824: 
                   2825: 5 constant foo
                   2826: foo .
                   2827: @end example
                   2828: 
                   2829: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   2830: @code{does>} replaces @code{;}, but it also does something else: It
                   2831: changes the last defined word such that it pushes the address of the
                   2832: body of the word and then performs the code after the @code{does>}
                   2833: whenever it is called.
                   2834: 
                   2835: In the example above, @code{constant} uses @code{,} to store 5 into the
                   2836: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   2837: the body onto the stack, then (in the code after the @code{does>})
                   2838: fetches the 5 from there.
                   2839: 
                   2840: The stack comment near the @code{does>} reflects the stack effect of the
                   2841: defined word, not the stack effect of the code after the @code{does>}
                   2842: (the difference is that the code expects the address of the body that
                   2843: the stack comment does not show).
                   2844: 
                   2845: You can use these definition words to do factoring in cases that involve
                   2846: (other) definition words.  E.g., a field offset is always added to an
                   2847: address.  Instead of defining
                   2848: 
                   2849: @example
                   2850: 2 cells constant offset-field1
                   2851: @end example
                   2852: 
                   2853: and using this like
                   2854: 
                   2855: @example
                   2856: ( addr ) offset-field1 +
                   2857: @end example
                   2858: 
                   2859: you can define a definition word
                   2860: 
                   2861: @example
                   2862: : simple-field ( n "name" -- )
                   2863:   create ,
                   2864: does> ( n1 -- n1+n )
1.50      anton    2865:   ( addr ) @@ + ;
1.48      anton    2866: @end example
1.21      crook    2867: 
1.48      anton    2868: Definition and use of field offsets now look like this:
1.21      crook    2869: 
1.48      anton    2870: @example
                   2871: 2 cells simple-field field1
1.60      anton    2872: create mystruct 4 cells allot
                   2873: mystruct .s field1 .s drop
1.48      anton    2874: @end example
1.21      crook    2875: 
1.48      anton    2876: If you want to do something with the word without performing the code
                   2877: after the @code{does>}, you can access the body of a @code{create}d word
                   2878: with @code{>body ( xt -- addr )}:
1.21      crook    2879: 
1.48      anton    2880: @example
                   2881: : value ( n "name" -- )
                   2882:   create ,
                   2883: does> ( -- n1 )
1.50      anton    2884:   @@ ;
1.48      anton    2885: : to ( n "name" -- )
                   2886:   ' >body ! ;
1.21      crook    2887: 
1.48      anton    2888: 5 value foo
                   2889: foo .
                   2890: 7 to foo
                   2891: foo .
                   2892: @end example
1.21      crook    2893: 
1.48      anton    2894: @assignment
                   2895: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   2896: XT (at the start the XT of @code{abort}), and upon execution
                   2897: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   2898: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   2899: recursion is one application of @code{defer}.
                   2900: @endassignment
1.29      crook    2901: 
1.66      anton    2902: Reference: @ref{User-defined Defining Words}.
                   2903: 
                   2904: 
1.48      anton    2905: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   2906: @section Arrays and Records
1.66      anton    2907: @cindex arrays tutorial
                   2908: @cindex records tutorial
                   2909: @cindex structs tutorial
1.29      crook    2910: 
1.48      anton    2911: Forth has no standard words for defining data structures such as arrays
                   2912: and records (structs in C terminology), but you can build them yourself
                   2913: based on address arithmetic.  You can also define words for defining
                   2914: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    2915: 
1.48      anton    2916: One of the first projects a Forth newcomer sets out upon when learning
                   2917: about defining words is an array defining word (possibly for
                   2918: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   2919: learn something from it.  However, don't be disappointed when you later
                   2920: learn that you have little use for these words (inappropriate use would
                   2921: be even worse).  I have not yet found a set of useful array words yet;
                   2922: the needs are just too diverse, and named, global arrays (the result of
                   2923: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    2924: consider how to pass them as parameters).  Another such project is a set
                   2925: of words to help dealing with strings.
1.29      crook    2926: 
1.48      anton    2927: On the other hand, there is a useful set of record words, and it has
                   2928: been defined in @file{compat/struct.fs}; these words are predefined in
                   2929: Gforth.  They are explained in depth elsewhere in this manual (see
                   2930: @pxref{Structures}).  The @code{simple-field} example above is
                   2931: simplified variant of fields in this package.
1.21      crook    2932: 
                   2933: 
1.48      anton    2934: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   2935: @section @code{POSTPONE}
1.66      anton    2936: @cindex postpone tutorial
1.21      crook    2937: 
1.48      anton    2938: You can compile the compilation semantics (instead of compiling the
                   2939: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    2940: 
1.48      anton    2941: @example
                   2942: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   2943:  POSTPONE + ; immediate
1.48      anton    2944: : foo ( n1 n2 -- n )
                   2945:  MY-+ ;
                   2946: 1 2 foo .
                   2947: see foo
                   2948: @end example
1.21      crook    2949: 
1.48      anton    2950: During the definition of @code{foo} the text interpreter performs the
                   2951: compilation semantics of @code{MY-+}, which performs the compilation
                   2952: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   2953: 
                   2954: This example also displays separate stack comments for the compilation
                   2955: semantics and for the stack effect of the compiled code.  For words with
                   2956: default compilation semantics these stack effects are usually not
                   2957: displayed; the stack effect of the compilation semantics is always
                   2958: @code{( -- )} for these words, the stack effect for the compiled code is
                   2959: the stack effect of the interpretation semantics.
                   2960: 
                   2961: Note that the state of the interpreter does not come into play when
                   2962: performing the compilation semantics in this way.  You can also perform
                   2963: it interpretively, e.g.:
                   2964: 
                   2965: @example
                   2966: : foo2 ( n1 n2 -- n )
                   2967:  [ MY-+ ] ;
                   2968: 1 2 foo .
                   2969: see foo
                   2970: @end example
1.21      crook    2971: 
1.48      anton    2972: However, there are some broken Forth systems where this does not always
1.62      crook    2973: work, and therefore this practice was been declared non-standard in
1.48      anton    2974: 1999.
                   2975: @c !! repair.fs
                   2976: 
                   2977: Here is another example for using @code{POSTPONE}:
1.44      crook    2978: 
1.48      anton    2979: @example
                   2980: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   2981:  POSTPONE negate POSTPONE + ; immediate compile-only
                   2982: : bar ( n1 n2 -- n )
                   2983:   MY-- ;
                   2984: 2 1 bar .
                   2985: see bar
                   2986: @end example
1.21      crook    2987: 
1.48      anton    2988: You can define @code{ENDIF} in this way:
1.21      crook    2989: 
1.48      anton    2990: @example
                   2991: : ENDIF ( Compilation: orig -- )
                   2992:   POSTPONE then ; immediate
                   2993: @end example
1.21      crook    2994: 
1.48      anton    2995: @assignment
                   2996: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   2997: @code{2dup}, but compiles @code{over over}.
                   2998: @endassignment
1.29      crook    2999: 
1.66      anton    3000: @c !! @xref{Macros} for reference
                   3001: 
                   3002: 
1.48      anton    3003: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3004: @section @code{Literal}
1.66      anton    3005: @cindex literal tutorial
1.29      crook    3006: 
1.48      anton    3007: You cannot @code{POSTPONE} numbers:
1.21      crook    3008: 
1.48      anton    3009: @example
                   3010: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3011: @end example
                   3012: 
1.48      anton    3013: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3014: 
1.48      anton    3015: @example
                   3016: : [FOO] ( compilation: --; run-time: -- n )
                   3017:   500 POSTPONE literal ; immediate
1.29      crook    3018: 
1.60      anton    3019: : flip [FOO] ;
1.48      anton    3020: flip .
                   3021: see flip
                   3022: @end example
1.29      crook    3023: 
1.48      anton    3024: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3025: semantics are executed) and pushes it at run-time (when the code it
                   3026: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3027: number computed at compile time into the current word:
1.29      crook    3028: 
1.48      anton    3029: @example
                   3030: : bar ( -- n )
                   3031:   [ 2 2 + ] literal ;
                   3032: see bar
                   3033: @end example
1.29      crook    3034: 
1.48      anton    3035: @assignment
                   3036: Write @code{]L} which allows writing the example above as @code{: bar (
                   3037: -- n ) [ 2 2 + ]L ;}
                   3038: @endassignment
                   3039: 
1.66      anton    3040: @c !! @xref{Macros} for reference
                   3041: 
1.48      anton    3042: 
                   3043: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3044: @section Advanced macros
1.66      anton    3045: @cindex macros, advanced tutorial
                   3046: @cindex run-time code generation, tutorial
1.48      anton    3047: 
1.66      anton    3048: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3049: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3050: expensive operation in some Forth implementations.  You can use
1.48      anton    3051: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3052: and produce a word that contains the word to be performed directly:
                   3053: 
                   3054: @c use ]] ... [[
                   3055: @example
                   3056: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3057: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3058: \ array beginning at addr and containing u elements
                   3059:   @{ xt @}
                   3060:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3061:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3062:   1 cells POSTPONE literal POSTPONE +loop ;
                   3063: 
                   3064: : sum-array ( addr u -- n )
                   3065:  0 rot rot [ ' + compile-map-array ] ;
                   3066: see sum-array
                   3067: a 5 sum-array .
                   3068: @end example
                   3069: 
                   3070: You can use the full power of Forth for generating the code; here's an
                   3071: example where the code is generated in a loop:
                   3072: 
                   3073: @example
                   3074: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3075: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3076:   POSTPONE tuck POSTPONE @@
1.48      anton    3077:   POSTPONE literal POSTPONE * POSTPONE +
                   3078:   POSTPONE swap POSTPONE cell+ ;
                   3079: 
                   3080: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3081: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3082:   0 postpone literal postpone swap
                   3083:   [ ' compile-vmul-step compile-map-array ]
                   3084:   postpone drop ;
                   3085: see compile-vmul
                   3086: 
                   3087: : a-vmul ( addr -- n )
1.51      pazsan   3088: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3089:  [ a 5 compile-vmul ] ;
                   3090: see a-vmul
                   3091: a a-vmul .
                   3092: @end example
                   3093: 
                   3094: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3095: also use @code{map-array} instead (try it now!).
1.48      anton    3096: 
                   3097: You can use this technique for efficient multiplication of large
                   3098: matrices.  In matrix multiplication, you multiply every line of one
                   3099: matrix with every column of the other matrix.  You can generate the code
                   3100: for one line once, and use it for every column.  The only downside of
                   3101: this technique is that it is cumbersome to recover the memory consumed
                   3102: by the generated code when you are done (and in more complicated cases
                   3103: it is not possible portably).
                   3104: 
1.66      anton    3105: @c !! @xref{Macros} for reference
                   3106: 
                   3107: 
1.48      anton    3108: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3109: @section Compilation Tokens
1.66      anton    3110: @cindex compilation tokens, tutorial
                   3111: @cindex CT, tutorial
1.48      anton    3112: 
                   3113: This section is Gforth-specific.  You can skip it.
                   3114: 
                   3115: @code{' word compile,} compiles the interpretation semantics.  For words
                   3116: with default compilation semantics this is the same as performing the
                   3117: compilation semantics.  To represent the compilation semantics of other
                   3118: words (e.g., words like @code{if} that have no interpretation
                   3119: semantics), Gforth has the concept of a compilation token (CT,
                   3120: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3121: You can perform the compilation semantics represented by a CT with
                   3122: @code{execute}:
1.29      crook    3123: 
1.48      anton    3124: @example
                   3125: : foo2 ( n1 n2 -- n )
                   3126:    [ comp' + execute ] ;
                   3127: see foo
                   3128: @end example
1.29      crook    3129: 
1.48      anton    3130: You can compile the compilation semantics represented by a CT with
                   3131: @code{postpone,}:
1.30      anton    3132: 
1.48      anton    3133: @example
                   3134: : foo3 ( -- )
                   3135:   [ comp' + postpone, ] ;
                   3136: see foo3
                   3137: @end example
1.30      anton    3138: 
1.51      pazsan   3139: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3140: @code{comp'} is particularly useful for words that have no
                   3141: interpretation semantics:
1.29      crook    3142: 
1.30      anton    3143: @example
1.48      anton    3144: ' if
1.60      anton    3145: comp' if .s 2drop
1.30      anton    3146: @end example
                   3147: 
1.66      anton    3148: Reference: @ref{Tokens for Words}.
                   3149: 
1.29      crook    3150: 
1.48      anton    3151: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3152: @section Wordlists and Search Order
1.66      anton    3153: @cindex wordlists tutorial
                   3154: @cindex search order, tutorial
1.48      anton    3155: 
                   3156: The dictionary is not just a memory area that allows you to allocate
                   3157: memory with @code{allot}, it also contains the Forth words, arranged in
                   3158: several wordlists.  When searching for a word in a wordlist,
                   3159: conceptually you start searching at the youngest and proceed towards
                   3160: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3161: you define a word with the same name as an older word, the new word
                   3162: shadows the older word.
                   3163: 
                   3164: Which wordlists are searched in which order is determined by the search
                   3165: order.  You can display the search order with @code{order}.  It displays
                   3166: first the search order, starting with the wordlist searched first, then
                   3167: it displays the wordlist that will contain newly defined words.
1.21      crook    3168: 
1.48      anton    3169: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3170: 
1.48      anton    3171: @example
                   3172: wordlist constant mywords
                   3173: @end example
1.21      crook    3174: 
1.48      anton    3175: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3176: defined words (the @emph{current} wordlist):
1.21      crook    3177: 
1.48      anton    3178: @example
                   3179: mywords set-current
                   3180: order
                   3181: @end example
1.26      crook    3182: 
1.48      anton    3183: Gforth does not display a name for the wordlist in @code{mywords}
                   3184: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3185: 
1.48      anton    3186: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3187: you want to put something into a specific wordlist without overall
                   3188: effect on the current wordlist, this typically looks like this:
1.21      crook    3189: 
1.48      anton    3190: @example
                   3191: get-current mywords set-current ( wid )
                   3192: create someword
                   3193: ( wid ) set-current
                   3194: @end example
1.21      crook    3195: 
1.48      anton    3196: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3197: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3198: searched wordlist is topmost.
1.21      crook    3199: 
1.48      anton    3200: @example
                   3201: get-order mywords swap 1+ set-order
                   3202: order
                   3203: @end example
1.21      crook    3204: 
1.48      anton    3205: Yes, the order of wordlists in the output of @code{order} is reversed
                   3206: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3207: 
1.48      anton    3208: @assignment
                   3209: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3210: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3211: removes the first searched wordlist from the search order.  Experiment
                   3212: with boundary conditions (you will see some crashes or situations that
                   3213: are hard or impossible to leave).
                   3214: @endassignment
1.21      crook    3215: 
1.48      anton    3216: The search order is a powerful foundation for providing features similar
                   3217: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3218: programs in this way has disadvantages for debugging and reuse/factoring
                   3219: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3220: though).  These disadvantages are not so clear in other
1.82      anton    3221: languages/programming environments, because these languages are not so
1.48      anton    3222: strong in debugging and reuse.
1.21      crook    3223: 
1.66      anton    3224: @c !! example
                   3225: 
                   3226: Reference: @ref{Word Lists}.
1.21      crook    3227: 
1.29      crook    3228: @c ******************************************************************
1.48      anton    3229: @node Introduction, Words, Tutorial, Top
1.29      crook    3230: @comment node-name,     next,           previous, up
                   3231: @chapter An Introduction to ANS Forth
                   3232: @cindex Forth - an introduction
1.21      crook    3233: 
1.83      anton    3234: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3235: that it is slower-paced in its examples, but uses them to dive deep into
                   3236: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3237: that, this chapter covers far less material.  It is suitable for reading
                   3238: without using a computer.
                   3239: 
1.29      crook    3240: The primary purpose of this manual is to document Gforth. However, since
                   3241: Forth is not a widely-known language and there is a lack of up-to-date
                   3242: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3243: material.  For other sources of Forth-related
                   3244: information, see @ref{Forth-related information}.
1.21      crook    3245: 
1.29      crook    3246: The examples in this section should work on any ANS Forth; the
                   3247: output shown was produced using Gforth. Each example attempts to
                   3248: reproduce the exact output that Gforth produces. If you try out the
                   3249: examples (and you should), what you should type is shown @kbd{like this}
                   3250: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3251: that, where the example shows @key{RET} it means that you should
1.29      crook    3252: press the ``carriage return'' key. Unfortunately, some output formats for
                   3253: this manual cannot show the difference between @kbd{this} and
                   3254: @code{this} which will make trying out the examples harder (but not
                   3255: impossible).
1.21      crook    3256: 
1.29      crook    3257: Forth is an unusual language. It provides an interactive development
                   3258: environment which includes both an interpreter and compiler. Forth
                   3259: programming style encourages you to break a problem down into many
                   3260: @cindex factoring
                   3261: small fragments (@dfn{factoring}), and then to develop and test each
                   3262: fragment interactively. Forth advocates assert that breaking the
                   3263: edit-compile-test cycle used by conventional programming languages can
                   3264: lead to great productivity improvements.
1.21      crook    3265: 
1.29      crook    3266: @menu
1.67      anton    3267: * Introducing the Text Interpreter::  
                   3268: * Stacks and Postfix notation::  
                   3269: * Your first definition::       
                   3270: * How does that work?::         
                   3271: * Forth is written in Forth::   
                   3272: * Review - elements of a Forth system::  
                   3273: * Where to go next::            
                   3274: * Exercises::                   
1.29      crook    3275: @end menu
1.21      crook    3276: 
1.29      crook    3277: @comment ----------------------------------------------
                   3278: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3279: @section Introducing the Text Interpreter
                   3280: @cindex text interpreter
                   3281: @cindex outer interpreter
1.21      crook    3282: 
1.30      anton    3283: @c IMO this is too detailed and the pace is too slow for
                   3284: @c an introduction.  If you know German, take a look at
                   3285: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3286: @c to see how I do it - anton 
                   3287: 
1.44      crook    3288: @c nac-> Where I have accepted your comments 100% and modified the text
                   3289: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3290: @c response like this to attempt to rationalise what I have done. Of
                   3291: @c course, this is a very clumsy mechanism for something that would be
                   3292: @c done far more efficiently over a beer. Please delete any dialogue
                   3293: @c you consider closed.
                   3294: 
1.29      crook    3295: When you invoke the Forth image, you will see a startup banner printed
                   3296: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3297: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3298: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3299: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3300: about the text interpreter as you read through this chapter, for more
                   3301: detail @pxref{The Text Interpreter}).
1.21      crook    3302: 
1.29      crook    3303: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3304: input. Type a number and press the @key{RET} key:
1.21      crook    3305: 
1.26      crook    3306: @example
1.30      anton    3307: @kbd{45@key{RET}}  ok
1.26      crook    3308: @end example
1.21      crook    3309: 
1.29      crook    3310: Rather than give you a prompt to invite you to input something, the text
                   3311: interpreter prints a status message @i{after} it has processed a line
                   3312: of input. The status message in this case (``@code{ ok}'' followed by
                   3313: carriage-return) indicates that the text interpreter was able to process
                   3314: all of your input successfully. Now type something illegal:
                   3315: 
                   3316: @example
1.30      anton    3317: @kbd{qwer341@key{RET}}
1.29      crook    3318: :1: Undefined word
                   3319: qwer341
                   3320: ^^^^^^^
                   3321: $400D2BA8 Bounce
                   3322: $400DBDA8 no.extensions
                   3323: @end example
1.23      crook    3324: 
1.29      crook    3325: The exact text, other than the ``Undefined word'' may differ slightly on
                   3326: your system, but the effect is the same; when the text interpreter
                   3327: detects an error, it discards any remaining text on a line, resets
1.49      anton    3328: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
                   3329: messages}.
1.23      crook    3330: 
1.29      crook    3331: The text interpreter waits for you to press carriage-return, and then
                   3332: processes your input line. Starting at the beginning of the line, it
                   3333: breaks the line into groups of characters separated by spaces. For each
                   3334: group of characters in turn, it makes two attempts to do something:
1.23      crook    3335: 
1.29      crook    3336: @itemize @bullet
                   3337: @item
1.44      crook    3338: @cindex name dictionary
1.29      crook    3339: It tries to treat it as a command. It does this by searching a @dfn{name
                   3340: dictionary}. If the group of characters matches an entry in the name
                   3341: dictionary, the name dictionary provides the text interpreter with
                   3342: information that allows the text interpreter perform some actions. In
                   3343: Forth jargon, we say that the group
                   3344: @cindex word
                   3345: @cindex definition
                   3346: @cindex execution token
                   3347: @cindex xt
                   3348: of characters names a @dfn{word}, that the dictionary search returns an
                   3349: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3350: word, and that the text interpreter executes the xt. Often, the terms
                   3351: @dfn{word} and @dfn{definition} are used interchangeably.
                   3352: @item
                   3353: If the text interpreter fails to find a match in the name dictionary, it
                   3354: tries to treat the group of characters as a number in the current number
                   3355: base (when you start up Forth, the current number base is base 10). If
                   3356: the group of characters legitimately represents a number, the text
                   3357: interpreter pushes the number onto a stack (we'll learn more about that
                   3358: in the next section).
                   3359: @end itemize
1.23      crook    3360: 
1.29      crook    3361: If the text interpreter is unable to do either of these things with any
                   3362: group of characters, it discards the group of characters and the rest of
                   3363: the line, then prints an error message. If the text interpreter reaches
                   3364: the end of the line without error, it prints the status message ``@code{ ok}''
                   3365: followed by carriage-return.
1.21      crook    3366: 
1.29      crook    3367: This is the simplest command we can give to the text interpreter:
1.23      crook    3368: 
                   3369: @example
1.30      anton    3370: @key{RET}  ok
1.23      crook    3371: @end example
1.21      crook    3372: 
1.29      crook    3373: The text interpreter did everything we asked it to do (nothing) without
                   3374: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3375: command:
1.21      crook    3376: 
1.23      crook    3377: @example
1.30      anton    3378: @kbd{12 dup fred dup@key{RET}}
1.29      crook    3379: :1: Undefined word
                   3380: 12 dup fred dup
                   3381:        ^^^^
                   3382: $400D2BA8 Bounce
                   3383: $400DBDA8 no.extensions
1.23      crook    3384: @end example
1.21      crook    3385: 
1.29      crook    3386: When you press the carriage-return key, the text interpreter starts to
                   3387: work its way along the line:
1.21      crook    3388: 
1.29      crook    3389: @itemize @bullet
                   3390: @item
                   3391: When it gets to the space after the @code{2}, it takes the group of
                   3392: characters @code{12} and looks them up in the name
                   3393: dictionary@footnote{We can't tell if it found them or not, but assume
                   3394: for now that it did not}. There is no match for this group of characters
                   3395: in the name dictionary, so it tries to treat them as a number. It is
                   3396: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3397: (whatever that means).
                   3398: @item
                   3399: The text interpreter resumes scanning the line and gets the next group
                   3400: of characters, @code{dup}. It looks it up in the name dictionary and
                   3401: (you'll have to take my word for this) finds it, and executes the word
                   3402: @code{dup} (whatever that means).
                   3403: @item
                   3404: Once again, the text interpreter resumes scanning the line and gets the
                   3405: group of characters @code{fred}. It looks them up in the name
                   3406: dictionary, but can't find them. It tries to treat them as a number, but
                   3407: they don't represent any legal number.
                   3408: @end itemize
1.21      crook    3409: 
1.29      crook    3410: At this point, the text interpreter gives up and prints an error
                   3411: message. The error message shows exactly how far the text interpreter
                   3412: got in processing the line. In particular, it shows that the text
                   3413: interpreter made no attempt to do anything with the final character
                   3414: group, @code{dup}, even though we have good reason to believe that the
                   3415: text interpreter would have no problem looking that word up and
                   3416: executing it a second time.
1.21      crook    3417: 
                   3418: 
1.29      crook    3419: @comment ----------------------------------------------
                   3420: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3421: @section Stacks, postfix notation and parameter passing
                   3422: @cindex text interpreter
                   3423: @cindex outer interpreter
1.21      crook    3424: 
1.29      crook    3425: In procedural programming languages (like C and Pascal), the
                   3426: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3427: functions or procedures are called with @dfn{explicit parameters}. For
                   3428: example, in C we might write:
1.21      crook    3429: 
1.23      crook    3430: @example
1.29      crook    3431: total = total + new_volume(length,height,depth);
1.23      crook    3432: @end example
1.21      crook    3433: 
1.23      crook    3434: @noindent
1.29      crook    3435: where new_volume is a function-call to another piece of code, and total,
                   3436: length, height and depth are all variables. length, height and depth are
                   3437: parameters to the function-call.
1.21      crook    3438: 
1.29      crook    3439: In Forth, the equivalent of the function or procedure is the
                   3440: @dfn{definition} and parameters are implicitly passed between
                   3441: definitions using a shared stack that is visible to the
                   3442: programmer. Although Forth does support variables, the existence of the
                   3443: stack means that they are used far less often than in most other
                   3444: programming languages. When the text interpreter encounters a number, it
                   3445: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3446: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3447: used for any operation is implied unambiguously by the operation being
                   3448: performed. The stack used for all integer operations is called the @dfn{data
                   3449: stack} and, since this is the stack used most commonly, references to
                   3450: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3451: 
1.29      crook    3452: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3453: 
1.23      crook    3454: @example
1.30      anton    3455: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3456: @end example
1.21      crook    3457: 
1.29      crook    3458: Then this instructs the text interpreter to placed three numbers on the
                   3459: (data) stack. An analogy for the behaviour of the stack is to take a
                   3460: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3461: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3462: you take a card off the pile then, unless you're prepared to fiddle a
                   3463: bit, the card that you take off will be the 3 (``first-out''). The
                   3464: number that will be first-out of the stack is called the @dfn{top of
                   3465: stack}, which
                   3466: @cindex TOS definition
                   3467: is often abbreviated to @dfn{TOS}.
1.21      crook    3468: 
1.29      crook    3469: To understand how parameters are passed in Forth, consider the
                   3470: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3471: be surprised to learn that this definition performs addition. More
                   3472: precisely, it adds two number together and produces a result. Where does
                   3473: it get the two numbers from? It takes the top two numbers off the
                   3474: stack. Where does it place the result? On the stack. You can act-out the
                   3475: behaviour of @code{+} with your playing cards like this:
1.21      crook    3476: 
                   3477: @itemize @bullet
                   3478: @item
1.29      crook    3479: Pick up two cards from the stack on the table
1.21      crook    3480: @item
1.29      crook    3481: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3482: numbers''
1.21      crook    3483: @item
1.29      crook    3484: Decide that the answer is 5
1.21      crook    3485: @item
1.29      crook    3486: Shuffle the two cards back into the pack and find a 5
1.21      crook    3487: @item
1.29      crook    3488: Put a 5 on the remaining ace that's on the table.
1.21      crook    3489: @end itemize
                   3490: 
1.29      crook    3491: If you don't have a pack of cards handy but you do have Forth running,
                   3492: you can use the definition @code{.s} to show the current state of the stack,
                   3493: without affecting the stack. Type:
1.21      crook    3494: 
                   3495: @example
1.30      anton    3496: @kbd{clearstack 1 2 3@key{RET}} ok
                   3497: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3498: @end example
                   3499: 
1.29      crook    3500: The text interpreter looks up the word @code{clearstack} and executes
                   3501: it; it tidies up the stack and removes any entries that may have been
                   3502: left on it by earlier examples. The text interpreter pushes each of the
                   3503: three numbers in turn onto the stack. Finally, the text interpreter
                   3504: looks up the word @code{.s} and executes it. The effect of executing
                   3505: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3506: followed by a list of all the items on the stack; the item on the far
                   3507: right-hand side is the TOS.
1.21      crook    3508: 
1.29      crook    3509: You can now type:
1.21      crook    3510: 
1.29      crook    3511: @example
1.30      anton    3512: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3513: @end example
1.21      crook    3514: 
1.29      crook    3515: @noindent
                   3516: which is correct; there are now 2 items on the stack and the result of
                   3517: the addition is 5.
1.23      crook    3518: 
1.29      crook    3519: If you're playing with cards, try doing a second addition: pick up the
                   3520: two cards, work out that their sum is 6, shuffle them into the pack,
                   3521: look for a 6 and place that on the table. You now have just one item on
                   3522: the stack. What happens if you try to do a third addition? Pick up the
                   3523: first card, pick up the second card -- ah! There is no second card. This
                   3524: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95      anton    3525: do the same thing with Forth it often reports an error (probably a Stack
1.29      crook    3526: Underflow or an Invalid Memory Address error).
1.23      crook    3527: 
1.29      crook    3528: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3529: which simply accepts that there is a finite amount of storage space
                   3530: reserved for the stack. To stretch the playing card analogy, if you had
                   3531: enough packs of cards and you piled the cards up on the table, you would
                   3532: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3533: allows you to set the maximum size of the stacks. In general, the only
                   3534: time that you will get a stack overflow is because a definition has a
                   3535: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3536: 
1.29      crook    3537: There's one final use for the playing card analogy. If you model your
                   3538: stack using a pack of playing cards, the maximum number of items on
                   3539: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3540: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3541: possible numbers are positive integer numbers 1 through 13; you can't
                   3542: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3543: think about some of the cards, you can accommodate different
                   3544: numbers. For example, you could think of the Jack as representing 0,
                   3545: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3546: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3547: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3548: 
1.29      crook    3549: In that analogy, the limit was the amount of information that a single
                   3550: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3551: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3552: implementation dependent and affects the maximum value that a stack
                   3553: entry can hold. A Standard Forth provides a cell size of at least
                   3554: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3555: 
1.29      crook    3556: Forth does not do any type checking for you, so you are free to
                   3557: manipulate and combine stack items in any way you wish. A convenient way
                   3558: of treating stack items is as 2's complement signed integers, and that
                   3559: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3560: 
1.29      crook    3561: @example
1.30      anton    3562: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3563: @end example
1.21      crook    3564: 
1.29      crook    3565: If you use numbers and definitions like @code{+} in order to turn Forth
                   3566: into a great big pocket calculator, you will realise that it's rather
                   3567: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3568: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3569: result). The terminology used to describe this difference is to say that
                   3570: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3571: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3572: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3573: 
1.29      crook    3574: Whilst postfix notation might look confusing to begin with, it has
                   3575: several important advantages:
1.21      crook    3576: 
1.23      crook    3577: @itemize @bullet
                   3578: @item
1.29      crook    3579: it is unambiguous
1.23      crook    3580: @item
1.29      crook    3581: it is more concise
1.23      crook    3582: @item
1.29      crook    3583: it fits naturally with a stack-based system
1.23      crook    3584: @end itemize
1.21      crook    3585: 
1.29      crook    3586: To examine these claims in more detail, consider these sums:
1.21      crook    3587: 
1.29      crook    3588: @example
                   3589: 6 + 5 * 4 =
                   3590: 4 * 5 + 6 =
                   3591: @end example
1.21      crook    3592: 
1.29      crook    3593: If you're just learning maths or your maths is very rusty, you will
                   3594: probably come up with the answer 44 for the first and 26 for the
                   3595: second. If you are a bit of a whizz at maths you will remember the
                   3596: @i{convention} that multiplication takes precendence over addition, and
                   3597: you'd come up with the answer 26 both times. To explain the answer 26
                   3598: to someone who got the answer 44, you'd probably rewrite the first sum
                   3599: like this:
1.21      crook    3600: 
1.29      crook    3601: @example
                   3602: 6 + (5 * 4) =
                   3603: @end example
1.21      crook    3604: 
1.29      crook    3605: If what you really wanted was to perform the addition before the
                   3606: multiplication, you would have to use parentheses to force it.
1.21      crook    3607: 
1.29      crook    3608: If you did the first two sums on a pocket calculator you would probably
                   3609: get the right answers, unless you were very cautious and entered them using
                   3610: these keystroke sequences:
1.21      crook    3611: 
1.29      crook    3612: 6 + 5 = * 4 =
                   3613: 4 * 5 = + 6 =
1.21      crook    3614: 
1.29      crook    3615: Postfix notation is unambiguous because the order that the operators
                   3616: are applied is always explicit; that also means that parentheses are
                   3617: never required. The operators are @i{active} (the act of quoting the
                   3618: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3619: 
1.29      crook    3620: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3621: equivalent ways:
1.26      crook    3622: 
                   3623: @example
1.29      crook    3624: 6 5 4 * +      or:
                   3625: 5 4 * 6 +
1.26      crook    3626: @end example
1.23      crook    3627: 
1.29      crook    3628: An important thing that you should notice about this notation is that
                   3629: the @i{order} of the numbers does not change; if you want to subtract
                   3630: 2 from 10 you type @code{10 2 -}.
1.1       anton    3631: 
1.29      crook    3632: The reason that Forth uses postfix notation is very simple to explain: it
                   3633: makes the implementation extremely simple, and it follows naturally from
                   3634: using the stack as a mechanism for passing parameters. Another way of
                   3635: thinking about this is to realise that all Forth definitions are
                   3636: @i{active}; they execute as they are encountered by the text
                   3637: interpreter. The result of this is that the syntax of Forth is trivially
                   3638: simple.
1.1       anton    3639: 
                   3640: 
                   3641: 
1.29      crook    3642: @comment ----------------------------------------------
                   3643: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3644: @section Your first Forth definition
                   3645: @cindex first definition
1.1       anton    3646: 
1.29      crook    3647: Until now, the examples we've seen have been trivial; we've just been
                   3648: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3649: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3650: again@footnote{That's not quite true. If you press the up-arrow key on
                   3651: your keyboard you should be able to scroll back to any earlier command,
                   3652: edit it and re-enter it.} In this section we'll see how to add new
                   3653: words to Forth's vocabulary.
1.1       anton    3654: 
1.29      crook    3655: The easiest way to create a new word is to use a @dfn{colon
                   3656: definition}. We'll define a few and try them out before worrying too
                   3657: much about how they work. Try typing in these examples; be careful to
                   3658: copy the spaces accurately:
1.1       anton    3659: 
1.29      crook    3660: @example
                   3661: : add-two 2 + . ;
                   3662: : greet ." Hello and welcome" ;
                   3663: : demo 5 add-two ;
                   3664: @end example
1.1       anton    3665: 
1.29      crook    3666: @noindent
                   3667: Now try them out:
1.1       anton    3668: 
1.29      crook    3669: @example
1.30      anton    3670: @kbd{greet@key{RET}} Hello and welcome  ok
                   3671: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3672: @kbd{4 add-two@key{RET}} 6  ok
                   3673: @kbd{demo@key{RET}} 7  ok
                   3674: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3675: @end example
1.1       anton    3676: 
1.29      crook    3677: The first new thing that we've introduced here is the pair of words
                   3678: @code{:} and @code{;}. These are used to start and terminate a new
                   3679: definition, respectively. The first word after the @code{:} is the name
                   3680: for the new definition.
1.1       anton    3681: 
1.29      crook    3682: As you can see from the examples, a definition is built up of words that
                   3683: have already been defined; Forth makes no distinction between
                   3684: definitions that existed when you started the system up, and those that
                   3685: you define yourself.
1.1       anton    3686: 
1.29      crook    3687: The examples also introduce the words @code{.} (dot), @code{."}
                   3688: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3689: the stack and displays it. It's like @code{.s} except that it only
                   3690: displays the top item of the stack and it is destructive; after it has
                   3691: executed, the number is no longer on the stack. There is always one
                   3692: space printed after the number, and no spaces before it. Dot-quote
                   3693: defines a string (a sequence of characters) that will be printed when
                   3694: the word is executed. The string can contain any printable characters
                   3695: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3696: word but it acts as a delimiter (the way that delimiters work is
                   3697: described in the next section). Finally, @code{dup} duplicates the value
                   3698: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3699: 
1.29      crook    3700: We already know that the text interpreter searches through the
                   3701: dictionary to locate names. If you've followed the examples earlier, you
                   3702: will already have a definition called @code{add-two}. Lets try modifying
                   3703: it by typing in a new definition:
1.1       anton    3704: 
1.29      crook    3705: @example
1.30      anton    3706: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3707: @end example
1.5       anton    3708: 
1.29      crook    3709: Forth recognised that we were defining a word that already exists, and
                   3710: printed a message to warn us of that fact. Let's try out the new
                   3711: definition:
1.5       anton    3712: 
1.29      crook    3713: @example
1.30      anton    3714: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3715: @end example
1.1       anton    3716: 
1.29      crook    3717: @noindent
                   3718: All that we've actually done here, though, is to create a new
                   3719: definition, with a particular name. The fact that there was already a
                   3720: definition with the same name did not make any difference to the way
                   3721: that the new definition was created (except that Forth printed a warning
                   3722: message). The old definition of add-two still exists (try @code{demo}
                   3723: again to see that this is true). Any new definition will use the new
                   3724: definition of @code{add-two}, but old definitions continue to use the
                   3725: version that already existed at the time that they were @code{compiled}.
1.1       anton    3726: 
1.29      crook    3727: Before you go on to the next section, try defining and redefining some
                   3728: words of your own.
1.1       anton    3729: 
1.29      crook    3730: @comment ----------------------------------------------
                   3731: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3732: @section How does that work?
                   3733: @cindex parsing words
1.1       anton    3734: 
1.30      anton    3735: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3736: 
                   3737: @c Is it a good idea to talk about the interpretation semantics of a
                   3738: @c number? We don't have an xt to go along with it. - anton
                   3739: 
                   3740: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3741: @c be better to keep them (or add run-time semantics), to make it easier to
                   3742: @c explain what compilation semantics usually does. - anton
                   3743: 
1.44      crook    3744: @c nac-> I removed the term ``default compilation sematics'' from the
                   3745: @c introductory chapter. Removing ``execution semantics'' was making
                   3746: @c everything simpler to explain, then I think the use of this term made
                   3747: @c everything more complex again. I replaced it with ``default
                   3748: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3749: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    3750: @c flag set''.
                   3751: 
                   3752: @c anton: I have eliminated default semantics (except in one place where it
                   3753: @c means "default interpretation and compilation semantics"), because it
                   3754: @c makes no sense in the presence of combined words.  I reverted to
                   3755: @c "execution semantics" where necessary.
                   3756: 
                   3757: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    3758: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3759: @c what you think -- I know I have not addressed your primary concern
                   3760: @c that it is too heavy-going for an introduction. From what I understood
                   3761: @c of your course notes it looks as though they might be a good framework. 
                   3762: @c Things that I've tried to capture here are some things that came as a
                   3763: @c great revelation here when I first understood them. Also, I like the
                   3764: @c fact that a very simple code example shows up almost all of the issues
                   3765: @c that you need to understand to see how Forth works. That's unique and
                   3766: @c worthwhile to emphasise.
                   3767: 
1.83      anton    3768: @c anton: I think it's a good idea to present the details, especially those
                   3769: @c that you found to be a revelation, and probably the tutorial tries to be
                   3770: @c too superficial and does not get some of the things across that make
                   3771: @c Forth special.  I do believe that most of the time these things should
                   3772: @c be discussed at the end of a section or in separate sections instead of
                   3773: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   3774: @c defining words" leads in a completely different direction from the rest
                   3775: @c of the section).
                   3776: 
1.29      crook    3777: Now we're going to take another look at the definition of @code{add-two}
                   3778: from the previous section. From our knowledge of the way that the text
                   3779: interpreter works, we would have expected this result when we tried to
                   3780: define @code{add-two}:
1.21      crook    3781: 
1.29      crook    3782: @example
1.44      crook    3783: @kbd{: add-two 2 + . ;@key{RET}}
1.29      crook    3784:   ^^^^^^^
                   3785: Error: Undefined word
                   3786: @end example
1.28      crook    3787: 
1.29      crook    3788: The reason that this didn't happen is bound up in the way that @code{:}
                   3789: works. The word @code{:} does two special things. The first special
                   3790: thing that it does prevents the text interpreter from ever seeing the
                   3791: characters @code{add-two}. The text interpreter uses a variable called
                   3792: @cindex modifying >IN
1.44      crook    3793: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3794: input line. When it encounters the word @code{:} it behaves in exactly
                   3795: the same way as it does for any other word; it looks it up in the name
                   3796: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3797: looks at the input buffer, finds the word @code{add-two} and advances the
                   3798: value of @code{>IN} to point past it. It then does some other stuff
                   3799: associated with creating the new definition (including creating an entry
                   3800: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3801: completes, control returns to the text interpreter, which is oblivious
                   3802: to the fact that it has been tricked into ignoring part of the input
                   3803: line.
1.21      crook    3804: 
1.29      crook    3805: @cindex parsing words
                   3806: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3807: prevent the text interpreter from acting on the whole of the input line
                   3808: -- are called @dfn{parsing words}.
1.21      crook    3809: 
1.29      crook    3810: @cindex @code{state} - effect on the text interpreter
                   3811: @cindex text interpreter - effect of state
                   3812: The second special thing that @code{:} does is change the value of a
                   3813: variable called @code{state}, which affects the way that the text
                   3814: interpreter behaves. When Gforth starts up, @code{state} has the value
                   3815: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   3816: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    3817: the text interpreter is said to be @dfn{compiling}.
                   3818: 
                   3819: In this example, the text interpreter is compiling when it processes the
                   3820: string ``@code{2 + . ;}''. It still breaks the string down into
                   3821: character sequences in the same way. However, instead of pushing the
                   3822: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   3823: into the definition of @code{add-two} that will make the number @code{2} get
                   3824: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   3825: the behaviours of @code{+} and @code{.} are also compiled into the
                   3826: definition.
                   3827: 
                   3828: One category of words don't get compiled. These so-called @dfn{immediate
                   3829: words} get executed (performed @i{now}) regardless of whether the text
                   3830: interpreter is interpreting or compiling. The word @code{;} is an
                   3831: immediate word. Rather than being compiled into the definition, it
                   3832: executes. Its effect is to terminate the current definition, which
                   3833: includes changing the value of @code{state} back to 0.
                   3834: 
                   3835: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   3836: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   3837: definition.
1.28      crook    3838: 
1.30      anton    3839: In Forth, every word or number can be described in terms of two
1.29      crook    3840: properties:
1.28      crook    3841: 
                   3842: @itemize @bullet
                   3843: @item
1.29      crook    3844: @cindex interpretation semantics
1.44      crook    3845: Its @dfn{interpretation semantics} describe how it will behave when the
                   3846: text interpreter encounters it in @dfn{interpret} state. The
                   3847: interpretation semantics of a word are represented by an @dfn{execution
                   3848: token}.
1.28      crook    3849: @item
1.29      crook    3850: @cindex compilation semantics
1.44      crook    3851: Its @dfn{compilation semantics} describe how it will behave when the
                   3852: text interpreter encounters it in @dfn{compile} state. The compilation
                   3853: semantics of a word are represented in an implementation-dependent way;
                   3854: Gforth uses a @dfn{compilation token}.
1.29      crook    3855: @end itemize
                   3856: 
                   3857: @noindent
                   3858: Numbers are always treated in a fixed way:
                   3859: 
                   3860: @itemize @bullet
1.28      crook    3861: @item
1.44      crook    3862: When the number is @dfn{interpreted}, its behaviour is to push the
                   3863: number onto the stack.
1.28      crook    3864: @item
1.30      anton    3865: When the number is @dfn{compiled}, a piece of code is appended to the
                   3866: current definition that pushes the number when it runs. (In other words,
                   3867: the compilation semantics of a number are to postpone its interpretation
                   3868: semantics until the run-time of the definition that it is being compiled
                   3869: into.)
1.29      crook    3870: @end itemize
                   3871: 
1.44      crook    3872: Words don't behave in such a regular way, but most have @i{default
                   3873: semantics} which means that they behave like this:
1.29      crook    3874: 
                   3875: @itemize @bullet
1.28      crook    3876: @item
1.30      anton    3877: The @dfn{interpretation semantics} of the word are to do something useful.
                   3878: @item
1.29      crook    3879: The @dfn{compilation semantics} of the word are to append its
1.30      anton    3880: @dfn{interpretation semantics} to the current definition (so that its
                   3881: run-time behaviour is to do something useful).
1.28      crook    3882: @end itemize
                   3883: 
1.30      anton    3884: @cindex immediate words
1.44      crook    3885: The actual behaviour of any particular word can be controlled by using
                   3886: the words @code{immediate} and @code{compile-only} when the word is
                   3887: defined. These words set flags in the name dictionary entry of the most
                   3888: recently defined word, and these flags are retrieved by the text
                   3889: interpreter when it finds the word in the name dictionary.
                   3890: 
                   3891: A word that is marked as @dfn{immediate} has compilation semantics that
                   3892: are identical to its interpretation semantics. In other words, it
                   3893: behaves like this:
1.29      crook    3894: 
                   3895: @itemize @bullet
                   3896: @item
1.30      anton    3897: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    3898: @item
1.30      anton    3899: The @dfn{compilation semantics} of the word are to do something useful
                   3900: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    3901: @end itemize
1.28      crook    3902: 
1.44      crook    3903: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   3904: performing the interpretation semantics of the word directly; an attempt
                   3905: to do so will generate an error. It is never necessary to use
                   3906: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   3907: provided by many implementations) but it is good etiquette to apply it
                   3908: to a word that will not behave correctly (and might have unexpected
                   3909: side-effects) in interpret state. For example, it is only legal to use
                   3910: the conditional word @code{IF} within a definition. If you forget this
                   3911: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   3912: @code{compile-only} allows the text interpreter to generate a helpful
                   3913: error message rather than subjecting you to the consequences of your
                   3914: folly.
                   3915: 
1.29      crook    3916: This example shows the difference between an immediate and a
                   3917: non-immediate word:
1.28      crook    3918: 
1.29      crook    3919: @example
                   3920: : show-state state @@ . ;
                   3921: : show-state-now show-state ; immediate
                   3922: : word1 show-state ;
                   3923: : word2 show-state-now ;
1.28      crook    3924: @end example
1.23      crook    3925: 
1.29      crook    3926: The word @code{immediate} after the definition of @code{show-state-now}
                   3927: makes that word an immediate word. These definitions introduce a new
                   3928: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   3929: variable, and leaves it on the stack. Therefore, the behaviour of
                   3930: @code{show-state} is to print a number that represents the current value
                   3931: of @code{state}.
1.28      crook    3932: 
1.29      crook    3933: When you execute @code{word1}, it prints the number 0, indicating that
                   3934: the system is interpreting. When the text interpreter compiled the
                   3935: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    3936: compilation semantics are to append its interpretation semantics to the
1.29      crook    3937: current definition. When you execute @code{word1}, it performs the
1.30      anton    3938: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    3939: (and therefore @code{show-state}) are executed, the system is
                   3940: interpreting.
1.28      crook    3941: 
1.30      anton    3942: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    3943: you should have seen the number -1 printed, followed by ``@code{
                   3944: ok}''. When the text interpreter compiled the definition of
                   3945: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    3946: whose compilation semantics are therefore to perform its interpretation
1.29      crook    3947: semantics. It is executed straight away (even before the text
                   3948: interpreter has moved on to process another group of characters; the
                   3949: @code{;} in this example). The effect of executing it are to display the
                   3950: value of @code{state} @i{at the time that the definition of}
                   3951: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   3952: system is compiling at this time. If you execute @code{word2} it does
                   3953: nothing at all.
1.28      crook    3954: 
1.29      crook    3955: @cindex @code{."}, how it works
                   3956: Before leaving the subject of immediate words, consider the behaviour of
                   3957: @code{."} in the definition of @code{greet}, in the previous
                   3958: section. This word is both a parsing word and an immediate word. Notice
                   3959: that there is a space between @code{."} and the start of the text
                   3960: @code{Hello and welcome}, but that there is no space between the last
                   3961: letter of @code{welcome} and the @code{"} character. The reason for this
                   3962: is that @code{."} is a Forth word; it must have a space after it so that
                   3963: the text interpreter can identify it. The @code{"} is not a Forth word;
                   3964: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   3965: is displayed, there is neither a space before the @code{H} nor after the
                   3966: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   3967: that @code{greet} is defined. When it executes, its behaviour is to
                   3968: search forward in the input line looking for the delimiter. When it
                   3969: finds the delimiter, it updates @code{>IN} to point past the
                   3970: delimiter. It also compiles some magic code into the definition of
                   3971: @code{greet}; the xt of a run-time routine that prints a text string. It
                   3972: compiles the string @code{Hello and welcome} into memory so that it is
                   3973: available to be printed later. When the text interpreter gains control,
                   3974: the next word it finds in the input stream is @code{;} and so it
                   3975: terminates the definition of @code{greet}.
1.28      crook    3976: 
                   3977: 
                   3978: @comment ----------------------------------------------
1.29      crook    3979: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   3980: @section Forth is written in Forth
                   3981: @cindex structure of Forth programs
                   3982: 
                   3983: When you start up a Forth compiler, a large number of definitions
                   3984: already exist. In Forth, you develop a new application using bottom-up
                   3985: programming techniques to create new definitions that are defined in
                   3986: terms of existing definitions. As you create each definition you can
                   3987: test and debug it interactively.
                   3988: 
                   3989: If you have tried out the examples in this section, you will probably
                   3990: have typed them in by hand; when you leave Gforth, your definitions will
                   3991: be lost. You can avoid this by using a text editor to enter Forth source
                   3992: code into a file, and then loading code from the file using
1.49      anton    3993: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    3994: processed by the text interpreter, just as though you had typed it in by
                   3995: hand@footnote{Actually, there are some subtle differences -- see
                   3996: @ref{The Text Interpreter}.}.
                   3997: 
                   3998: Gforth also supports the traditional Forth alternative to using text
1.49      anton    3999: files for program entry (@pxref{Blocks}).
1.28      crook    4000: 
1.29      crook    4001: In common with many, if not most, Forth compilers, most of Gforth is
                   4002: actually written in Forth. All of the @file{.fs} files in the
                   4003: installation directory@footnote{For example,
1.30      anton    4004: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4005: study to see examples of Forth programming.
1.28      crook    4006: 
1.29      crook    4007: Gforth maintains a history file that records every line that you type to
                   4008: the text interpreter. This file is preserved between sessions, and is
                   4009: used to provide a command-line recall facility. If you enter long
                   4010: definitions by hand, you can use a text editor to paste them out of the
                   4011: history file into a Forth source file for reuse at a later time
1.49      anton    4012: (for more information @pxref{Command-line editing}).
1.28      crook    4013: 
                   4014: 
                   4015: @comment ----------------------------------------------
1.29      crook    4016: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4017: @section Review - elements of a Forth system
                   4018: @cindex elements of a Forth system
1.28      crook    4019: 
1.29      crook    4020: To summarise this chapter:
1.28      crook    4021: 
                   4022: @itemize @bullet
                   4023: @item
1.29      crook    4024: Forth programs use @dfn{factoring} to break a problem down into small
                   4025: fragments called @dfn{words} or @dfn{definitions}.
                   4026: @item
                   4027: Forth program development is an interactive process.
                   4028: @item
                   4029: The main command loop that accepts input, and controls both
                   4030: interpretation and compilation, is called the @dfn{text interpreter}
                   4031: (also known as the @dfn{outer interpreter}).
                   4032: @item
                   4033: Forth has a very simple syntax, consisting of words and numbers
                   4034: separated by spaces or carriage-return characters. Any additional syntax
                   4035: is imposed by @dfn{parsing words}.
                   4036: @item
                   4037: Forth uses a stack to pass parameters between words. As a result, it
                   4038: uses postfix notation.
                   4039: @item
                   4040: To use a word that has previously been defined, the text interpreter
                   4041: searches for the word in the @dfn{name dictionary}.
                   4042: @item
1.30      anton    4043: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4044: @item
1.29      crook    4045: The text interpreter uses the value of @code{state} to select between
                   4046: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4047: semantics} of a word that it encounters.
1.28      crook    4048: @item
1.30      anton    4049: The relationship between the @dfn{interpretation semantics} and
                   4050: @dfn{compilation semantics} for a word
1.29      crook    4051: depend upon the way in which the word was defined (for example, whether
                   4052: it is an @dfn{immediate} word).
1.28      crook    4053: @item
1.29      crook    4054: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4055: definitions}) or in some other way (usually a lower-level language and
                   4056: as a result often called @dfn{low-level definitions}, @dfn{code
                   4057: definitions} or @dfn{primitives}).
1.28      crook    4058: @item
1.29      crook    4059: Many Forth systems are implemented mainly in Forth.
1.28      crook    4060: @end itemize
                   4061: 
                   4062: 
1.29      crook    4063: @comment ----------------------------------------------
1.48      anton    4064: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4065: @section Where To Go Next
                   4066: @cindex where to go next
1.28      crook    4067: 
1.29      crook    4068: Amazing as it may seem, if you have read (and understood) this far, you
                   4069: know almost all the fundamentals about the inner workings of a Forth
                   4070: system. You certainly know enough to be able to read and understand the
                   4071: rest of this manual and the ANS Forth document, to learn more about the
                   4072: facilities that Forth in general and Gforth in particular provide. Even
                   4073: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4074: However, that's not a good idea just yet... better to try writing some
1.29      crook    4075: programs in Gforth.
1.28      crook    4076: 
1.29      crook    4077: Forth has such a rich vocabulary that it can be hard to know where to
                   4078: start in learning it. This section suggests a few sets of words that are
                   4079: enough to write small but useful programs. Use the word index in this
                   4080: document to learn more about each word, then try it out and try to write
                   4081: small definitions using it. Start by experimenting with these words:
1.28      crook    4082: 
                   4083: @itemize @bullet
                   4084: @item
1.29      crook    4085: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4086: @item
                   4087: Comparison: @code{MIN MAX =}
                   4088: @item
                   4089: Logic: @code{AND OR XOR NOT}
                   4090: @item
                   4091: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4092: @item
1.29      crook    4093: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4094: @item
1.29      crook    4095: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4096: @item
1.29      crook    4097: Defining words: @code{: ; CREATE}
1.28      crook    4098: @item
1.29      crook    4099: Memory allocation words: @code{ALLOT ,}
1.28      crook    4100: @item
1.29      crook    4101: Tools: @code{SEE WORDS .S MARKER}
                   4102: @end itemize
                   4103: 
                   4104: When you have mastered those, go on to:
                   4105: 
                   4106: @itemize @bullet
1.28      crook    4107: @item
1.29      crook    4108: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4109: @item
1.29      crook    4110: Memory access: @code{@@ !}
1.28      crook    4111: @end itemize
1.23      crook    4112: 
1.29      crook    4113: When you have mastered these, there's nothing for it but to read through
                   4114: the whole of this manual and find out what you've missed.
                   4115: 
                   4116: @comment ----------------------------------------------
1.48      anton    4117: @node Exercises,  , Where to go next, Introduction
1.29      crook    4118: @section Exercises
                   4119: @cindex exercises
                   4120: 
                   4121: TODO: provide a set of programming excercises linked into the stuff done
                   4122: already and into other sections of the manual. Provide solutions to all
                   4123: the exercises in a .fs file in the distribution.
                   4124: 
                   4125: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4126: 
                   4127: @c excercises:
                   4128: @c 1. take inches and convert to feet and inches.
                   4129: @c 2. take temperature and convert from fahrenheight to celcius;
                   4130: @c    may need to care about symmetric vs floored??
                   4131: @c 3. take input line and do character substitution
                   4132: @c    to encipher or decipher
                   4133: @c 4. as above but work on a file for in and out
                   4134: @c 5. take input line and convert to pig-latin 
                   4135: @c
                   4136: @c thing of sets of things to exercise then come up with
                   4137: @c problems that need those things.
                   4138: 
                   4139: 
1.26      crook    4140: @c ******************************************************************
1.29      crook    4141: @node Words, Error messages, Introduction, Top
1.1       anton    4142: @chapter Forth Words
1.26      crook    4143: @cindex words
1.1       anton    4144: 
                   4145: @menu
                   4146: * Notation::                    
1.65      anton    4147: * Case insensitivity::          
                   4148: * Comments::                    
                   4149: * Boolean Flags::               
1.1       anton    4150: * Arithmetic::                  
                   4151: * Stack Manipulation::          
1.5       anton    4152: * Memory::                      
1.1       anton    4153: * Control Structures::          
                   4154: * Defining Words::              
1.65      anton    4155: * Interpretation and Compilation Semantics::  
1.47      crook    4156: * Tokens for Words::            
1.81      anton    4157: * Compiling words::             
1.65      anton    4158: * The Text Interpreter::        
1.111     anton    4159: * The Input Stream::            
1.65      anton    4160: * Word Lists::                  
                   4161: * Environmental Queries::       
1.12      anton    4162: * Files::                       
                   4163: * Blocks::                      
                   4164: * Other I/O::                   
1.78      anton    4165: * Locals::                      
                   4166: * Structures::                  
                   4167: * Object-oriented Forth::       
1.12      anton    4168: * Programming Tools::           
                   4169: * Assembler and Code Words::    
                   4170: * Threading Words::             
1.65      anton    4171: * Passing Commands to the OS::  
                   4172: * Keeping track of Time::       
                   4173: * Miscellaneous Words::         
1.1       anton    4174: @end menu
                   4175: 
1.65      anton    4176: @node Notation, Case insensitivity, Words, Words
1.1       anton    4177: @section Notation
                   4178: @cindex notation of glossary entries
                   4179: @cindex format of glossary entries
                   4180: @cindex glossary notation format
                   4181: @cindex word glossary entry format
                   4182: 
                   4183: The Forth words are described in this section in the glossary notation
1.67      anton    4184: that has become a de-facto standard for Forth texts:
1.1       anton    4185: 
                   4186: @format
1.29      crook    4187: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4188: @end format
1.29      crook    4189: @i{Description}
1.1       anton    4190: 
                   4191: @table @var
                   4192: @item word
1.28      crook    4193: The name of the word.
1.1       anton    4194: 
                   4195: @item Stack effect
                   4196: @cindex stack effect
1.29      crook    4197: The stack effect is written in the notation @code{@i{before} --
                   4198: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4199: stack entries before and after the execution of the word. The rest of
                   4200: the stack is not touched by the word. The top of stack is rightmost,
                   4201: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4202: uses a separate floating point stack, but a unified stack
1.29      crook    4203: notation. Also, return stack effects are not shown in @i{stack
                   4204: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4205: the type and/or the function of the item. See below for a discussion of
                   4206: the types.
                   4207: 
                   4208: All words have two stack effects: A compile-time stack effect and a
                   4209: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4210: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4211: this standard behaviour, or the word does other unusual things at
                   4212: compile time, both stack effects are shown; otherwise only the run-time
                   4213: stack effect is shown.
                   4214: 
                   4215: @cindex pronounciation of words
                   4216: @item pronunciation
                   4217: How the word is pronounced.
                   4218: 
                   4219: @cindex wordset
1.67      anton    4220: @cindex environment wordset
1.1       anton    4221: @item wordset
1.21      crook    4222: The ANS Forth standard is divided into several word sets. A standard
                   4223: system need not support all of them. Therefore, in theory, the fewer
                   4224: word sets your program uses the more portable it will be. However, we
                   4225: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4226: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4227: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4228: describes words that will work in future releases of Gforth;
                   4229: @code{gforth-internal} words are more volatile. Environmental query
                   4230: strings are also displayed like words; you can recognize them by the
1.21      crook    4231: @code{environment} in the word set field.
1.1       anton    4232: 
                   4233: @item Description
                   4234: A description of the behaviour of the word.
                   4235: @end table
                   4236: 
                   4237: @cindex types of stack items
                   4238: @cindex stack item types
                   4239: The type of a stack item is specified by the character(s) the name
                   4240: starts with:
                   4241: 
                   4242: @table @code
                   4243: @item f
                   4244: @cindex @code{f}, stack item type
                   4245: Boolean flags, i.e. @code{false} or @code{true}.
                   4246: @item c
                   4247: @cindex @code{c}, stack item type
                   4248: Char
                   4249: @item w
                   4250: @cindex @code{w}, stack item type
                   4251: Cell, can contain an integer or an address
                   4252: @item n
                   4253: @cindex @code{n}, stack item type
                   4254: signed integer
                   4255: @item u
                   4256: @cindex @code{u}, stack item type
                   4257: unsigned integer
                   4258: @item d
                   4259: @cindex @code{d}, stack item type
                   4260: double sized signed integer
                   4261: @item ud
                   4262: @cindex @code{ud}, stack item type
                   4263: double sized unsigned integer
                   4264: @item r
                   4265: @cindex @code{r}, stack item type
                   4266: Float (on the FP stack)
1.21      crook    4267: @item a-
1.1       anton    4268: @cindex @code{a_}, stack item type
                   4269: Cell-aligned address
1.21      crook    4270: @item c-
1.1       anton    4271: @cindex @code{c_}, stack item type
                   4272: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4273: @item f-
1.1       anton    4274: @cindex @code{f_}, stack item type
                   4275: Float-aligned address
1.21      crook    4276: @item df-
1.1       anton    4277: @cindex @code{df_}, stack item type
                   4278: Address aligned for IEEE double precision float
1.21      crook    4279: @item sf-
1.1       anton    4280: @cindex @code{sf_}, stack item type
                   4281: Address aligned for IEEE single precision float
                   4282: @item xt
                   4283: @cindex @code{xt}, stack item type
                   4284: Execution token, same size as Cell
                   4285: @item wid
                   4286: @cindex @code{wid}, stack item type
1.21      crook    4287: Word list ID, same size as Cell
1.68      anton    4288: @item ior, wior
                   4289: @cindex ior type description
                   4290: @cindex wior type description
                   4291: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4292: @item f83name
                   4293: @cindex @code{f83name}, stack item type
                   4294: Pointer to a name structure
                   4295: @item "
                   4296: @cindex @code{"}, stack item type
1.12      anton    4297: string in the input stream (not on the stack). The terminating character
                   4298: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4299: quotes.
                   4300: @end table
                   4301: 
1.65      anton    4302: @comment ----------------------------------------------
                   4303: @node Case insensitivity, Comments, Notation, Words
                   4304: @section Case insensitivity
                   4305: @cindex case sensitivity
                   4306: @cindex upper and lower case
                   4307: 
                   4308: Gforth is case-insensitive; you can enter definitions and invoke
                   4309: Standard words using upper, lower or mixed case (however,
                   4310: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4311: options}).
                   4312: 
                   4313: ANS Forth only @i{requires} implementations to recognise Standard words
                   4314: when they are typed entirely in upper case. Therefore, a Standard
                   4315: program must use upper case for all Standard words. You can use whatever
                   4316: case you like for words that you define, but in a Standard program you
                   4317: have to use the words in the same case that you defined them.
                   4318: 
                   4319: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4320: wordlists, @pxref{Word Lists}).
                   4321: 
                   4322: Two people have asked how to convert Gforth to be case-sensitive; while
                   4323: we think this is a bad idea, you can change all wordlists into tables
                   4324: like this:
                   4325: 
                   4326: @example
                   4327: ' table-find forth-wordlist wordlist-map @ !
                   4328: @end example
                   4329: 
                   4330: Note that you now have to type the predefined words in the same case
                   4331: that we defined them, which are varying.  You may want to convert them
                   4332: to your favourite case before doing this operation (I won't explain how,
                   4333: because if you are even contemplating doing this, you'd better have
                   4334: enough knowledge of Forth systems to know this already).
                   4335: 
                   4336: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4337: @section Comments
1.26      crook    4338: @cindex comments
1.21      crook    4339: 
1.29      crook    4340: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4341: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4342: 
1.44      crook    4343: 
1.23      crook    4344: doc-(
1.21      crook    4345: doc-\
1.23      crook    4346: doc-\G
1.21      crook    4347: 
1.44      crook    4348: 
1.21      crook    4349: @node Boolean Flags, Arithmetic, Comments, Words
                   4350: @section Boolean Flags
1.26      crook    4351: @cindex Boolean flags
1.21      crook    4352: 
                   4353: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4354: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4355: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4356: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4357: @c on and off to Memory? 
                   4358: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4359: 
1.21      crook    4360: doc-true
                   4361: doc-false
1.29      crook    4362: doc-on
                   4363: doc-off
1.21      crook    4364: 
1.44      crook    4365: 
1.21      crook    4366: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4367: @section Arithmetic
                   4368: @cindex arithmetic words
                   4369: 
                   4370: @cindex division with potentially negative operands
                   4371: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4372: overflow on addition or multiplication, you may hear about division by
                   4373: zero if you are lucky. The operator is written after the operands, but
                   4374: the operands are still in the original order. I.e., the infix @code{2-1}
                   4375: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4376: operators. If you perform division with potentially negative operands,
                   4377: you do not want to use @code{/} or @code{/mod} with its undefined
                   4378: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4379: former, @pxref{Mixed precision}).
1.26      crook    4380: @comment TODO discuss the different division forms and the std approach
1.1       anton    4381: 
                   4382: @menu
                   4383: * Single precision::            
1.67      anton    4384: * Double precision::            Double-cell integer arithmetic
1.1       anton    4385: * Bitwise operations::          
1.67      anton    4386: * Numeric comparison::          
1.29      crook    4387: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4388: * Floating Point::              
                   4389: @end menu
                   4390: 
1.67      anton    4391: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4392: @subsection Single precision
                   4393: @cindex single precision arithmetic words
                   4394: 
1.67      anton    4395: @c !! cell undefined
                   4396: 
                   4397: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4398: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4399: treat them. For the rules used by the text interpreter for recognising
                   4400: single-precision integers see @ref{Number Conversion}.
1.21      crook    4401: 
1.67      anton    4402: These words are all defined for signed operands, but some of them also
                   4403: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4404: @code{*}.
1.44      crook    4405: 
1.1       anton    4406: doc-+
1.21      crook    4407: doc-1+
1.1       anton    4408: doc--
1.21      crook    4409: doc-1-
1.1       anton    4410: doc-*
                   4411: doc-/
                   4412: doc-mod
                   4413: doc-/mod
                   4414: doc-negate
                   4415: doc-abs
                   4416: doc-min
                   4417: doc-max
1.27      crook    4418: doc-floored
1.1       anton    4419: 
1.44      crook    4420: 
1.67      anton    4421: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4422: @subsection Double precision
                   4423: @cindex double precision arithmetic words
                   4424: 
1.49      anton    4425: For the rules used by the text interpreter for
                   4426: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4427: 
                   4428: A double precision number is represented by a cell pair, with the most
1.67      anton    4429: significant cell at the TOS. It is trivial to convert an unsigned single
                   4430: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4431: represented by Gforth using 2's complement arithmetic, converting a
                   4432: signed single to a (signed) double requires sign-extension across the
                   4433: most significant cell. This can be achieved using @code{s>d}. The moral
                   4434: of the story is that you cannot convert a number without knowing whether
                   4435: it represents an unsigned or a signed number.
1.21      crook    4436: 
1.67      anton    4437: These words are all defined for signed operands, but some of them also
                   4438: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4439: 
1.21      crook    4440: doc-s>d
1.67      anton    4441: doc-d>s
1.21      crook    4442: doc-d+
                   4443: doc-d-
                   4444: doc-dnegate
                   4445: doc-dabs
                   4446: doc-dmin
                   4447: doc-dmax
                   4448: 
1.44      crook    4449: 
1.67      anton    4450: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4451: @subsection Bitwise operations
                   4452: @cindex bitwise operation words
                   4453: 
                   4454: 
                   4455: doc-and
                   4456: doc-or
                   4457: doc-xor
                   4458: doc-invert
                   4459: doc-lshift
                   4460: doc-rshift
                   4461: doc-2*
                   4462: doc-d2*
                   4463: doc-2/
                   4464: doc-d2/
                   4465: 
                   4466: 
                   4467: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4468: @subsection Numeric comparison
                   4469: @cindex numeric comparison words
                   4470: 
1.67      anton    4471: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4472: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4473: 
1.28      crook    4474: doc-<
                   4475: doc-<=
                   4476: doc-<>
                   4477: doc-=
                   4478: doc->
                   4479: doc->=
                   4480: 
1.21      crook    4481: doc-0<
1.23      crook    4482: doc-0<=
1.21      crook    4483: doc-0<>
                   4484: doc-0=
1.23      crook    4485: doc-0>
                   4486: doc-0>=
1.28      crook    4487: 
                   4488: doc-u<
                   4489: doc-u<=
1.44      crook    4490: @c u<> and u= exist but are the same as <> and =
1.31      anton    4491: @c doc-u<>
                   4492: @c doc-u=
1.28      crook    4493: doc-u>
                   4494: doc-u>=
                   4495: 
                   4496: doc-within
                   4497: 
                   4498: doc-d<
                   4499: doc-d<=
                   4500: doc-d<>
                   4501: doc-d=
                   4502: doc-d>
                   4503: doc-d>=
1.23      crook    4504: 
1.21      crook    4505: doc-d0<
1.23      crook    4506: doc-d0<=
                   4507: doc-d0<>
1.21      crook    4508: doc-d0=
1.23      crook    4509: doc-d0>
                   4510: doc-d0>=
                   4511: 
1.21      crook    4512: doc-du<
1.28      crook    4513: doc-du<=
1.44      crook    4514: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4515: @c doc-du<>
                   4516: @c doc-du=
1.28      crook    4517: doc-du>
                   4518: doc-du>=
1.1       anton    4519: 
1.44      crook    4520: 
1.21      crook    4521: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4522: @subsection Mixed precision
                   4523: @cindex mixed precision arithmetic words
                   4524: 
1.44      crook    4525: 
1.1       anton    4526: doc-m+
                   4527: doc-*/
                   4528: doc-*/mod
                   4529: doc-m*
                   4530: doc-um*
                   4531: doc-m*/
                   4532: doc-um/mod
                   4533: doc-fm/mod
                   4534: doc-sm/rem
                   4535: 
1.44      crook    4536: 
1.21      crook    4537: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4538: @subsection Floating Point
                   4539: @cindex floating point arithmetic words
                   4540: 
1.49      anton    4541: For the rules used by the text interpreter for
                   4542: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4543: 
1.67      anton    4544: Gforth has a separate floating point stack, but the documentation uses
                   4545: the unified notation.@footnote{It's easy to generate the separate
                   4546: notation from that by just separating the floating-point numbers out:
                   4547: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4548: r3 )}.}
1.1       anton    4549: 
                   4550: @cindex floating-point arithmetic, pitfalls
                   4551: Floating point numbers have a number of unpleasant surprises for the
                   4552: unwary (e.g., floating point addition is not associative) and even a few
                   4553: for the wary. You should not use them unless you know what you are doing
                   4554: or you don't care that the results you get are totally bogus. If you
                   4555: want to learn about the problems of floating point numbers (and how to
1.66      anton    4556: avoid them), you might start with @cite{David Goldberg,
                   4557: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
                   4558: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
                   4559: Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4560: 
1.44      crook    4561: 
1.21      crook    4562: doc-d>f
                   4563: doc-f>d
1.1       anton    4564: doc-f+
                   4565: doc-f-
                   4566: doc-f*
                   4567: doc-f/
                   4568: doc-fnegate
                   4569: doc-fabs
                   4570: doc-fmax
                   4571: doc-fmin
                   4572: doc-floor
                   4573: doc-fround
                   4574: doc-f**
                   4575: doc-fsqrt
                   4576: doc-fexp
                   4577: doc-fexpm1
                   4578: doc-fln
                   4579: doc-flnp1
                   4580: doc-flog
                   4581: doc-falog
1.32      anton    4582: doc-f2*
                   4583: doc-f2/
                   4584: doc-1/f
                   4585: doc-precision
                   4586: doc-set-precision
                   4587: 
                   4588: @cindex angles in trigonometric operations
                   4589: @cindex trigonometric operations
                   4590: Angles in floating point operations are given in radians (a full circle
                   4591: has 2 pi radians).
                   4592: 
1.1       anton    4593: doc-fsin
                   4594: doc-fcos
                   4595: doc-fsincos
                   4596: doc-ftan
                   4597: doc-fasin
                   4598: doc-facos
                   4599: doc-fatan
                   4600: doc-fatan2
                   4601: doc-fsinh
                   4602: doc-fcosh
                   4603: doc-ftanh
                   4604: doc-fasinh
                   4605: doc-facosh
                   4606: doc-fatanh
1.21      crook    4607: doc-pi
1.28      crook    4608: 
1.32      anton    4609: @cindex equality of floats
                   4610: @cindex floating-point comparisons
1.31      anton    4611: One particular problem with floating-point arithmetic is that comparison
                   4612: for equality often fails when you would expect it to succeed.  For this
                   4613: reason approximate equality is often preferred (but you still have to
1.67      anton    4614: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4615: differently from what you might expect.  The comparison words are:
1.31      anton    4616: 
                   4617: doc-f~rel
                   4618: doc-f~abs
1.68      anton    4619: doc-f~
1.31      anton    4620: doc-f=
                   4621: doc-f<>
                   4622: 
                   4623: doc-f<
                   4624: doc-f<=
                   4625: doc-f>
                   4626: doc-f>=
                   4627: 
1.21      crook    4628: doc-f0<
1.28      crook    4629: doc-f0<=
                   4630: doc-f0<>
1.21      crook    4631: doc-f0=
1.28      crook    4632: doc-f0>
                   4633: doc-f0>=
                   4634: 
1.1       anton    4635: 
                   4636: @node Stack Manipulation, Memory, Arithmetic, Words
                   4637: @section Stack Manipulation
                   4638: @cindex stack manipulation words
                   4639: 
                   4640: @cindex floating-point stack in the standard
1.21      crook    4641: Gforth maintains a number of separate stacks:
                   4642: 
1.29      crook    4643: @cindex data stack
                   4644: @cindex parameter stack
1.21      crook    4645: @itemize @bullet
                   4646: @item
1.29      crook    4647: A data stack (also known as the @dfn{parameter stack}) -- for
                   4648: characters, cells, addresses, and double cells.
1.21      crook    4649: 
1.29      crook    4650: @cindex floating-point stack
1.21      crook    4651: @item
1.44      crook    4652: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4653: 
1.29      crook    4654: @cindex return stack
1.21      crook    4655: @item
1.44      crook    4656: A return stack -- for holding the return addresses of colon
1.32      anton    4657: definitions and other (non-FP) data.
1.21      crook    4658: 
1.29      crook    4659: @cindex locals stack
1.21      crook    4660: @item
1.44      crook    4661: A locals stack -- for holding local variables.
1.21      crook    4662: @end itemize
                   4663: 
1.1       anton    4664: @menu
                   4665: * Data stack::                  
                   4666: * Floating point stack::        
                   4667: * Return stack::                
                   4668: * Locals stack::                
                   4669: * Stack pointer manipulation::  
                   4670: @end menu
                   4671: 
                   4672: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4673: @subsection Data stack
                   4674: @cindex data stack manipulation words
                   4675: @cindex stack manipulations words, data stack
                   4676: 
1.44      crook    4677: 
1.1       anton    4678: doc-drop
                   4679: doc-nip
                   4680: doc-dup
                   4681: doc-over
                   4682: doc-tuck
                   4683: doc-swap
1.21      crook    4684: doc-pick
1.1       anton    4685: doc-rot
                   4686: doc--rot
                   4687: doc-?dup
                   4688: doc-roll
                   4689: doc-2drop
                   4690: doc-2nip
                   4691: doc-2dup
                   4692: doc-2over
                   4693: doc-2tuck
                   4694: doc-2swap
                   4695: doc-2rot
                   4696: 
1.44      crook    4697: 
1.1       anton    4698: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4699: @subsection Floating point stack
                   4700: @cindex floating-point stack manipulation words
                   4701: @cindex stack manipulation words, floating-point stack
                   4702: 
1.32      anton    4703: Whilst every sane Forth has a separate floating-point stack, it is not
                   4704: strictly required; an ANS Forth system could theoretically keep
                   4705: floating-point numbers on the data stack. As an additional difficulty,
                   4706: you don't know how many cells a floating-point number takes. It is
                   4707: reportedly possible to write words in a way that they work also for a
                   4708: unified stack model, but we do not recommend trying it. Instead, just
                   4709: say that your program has an environmental dependency on a separate
                   4710: floating-point stack.
                   4711: 
                   4712: doc-floating-stack
                   4713: 
1.1       anton    4714: doc-fdrop
                   4715: doc-fnip
                   4716: doc-fdup
                   4717: doc-fover
                   4718: doc-ftuck
                   4719: doc-fswap
1.21      crook    4720: doc-fpick
1.1       anton    4721: doc-frot
                   4722: 
1.44      crook    4723: 
1.1       anton    4724: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4725: @subsection Return stack
                   4726: @cindex return stack manipulation words
                   4727: @cindex stack manipulation words, return stack
                   4728: 
1.32      anton    4729: @cindex return stack and locals
                   4730: @cindex locals and return stack
                   4731: A Forth system is allowed to keep local variables on the
                   4732: return stack. This is reasonable, as local variables usually eliminate
                   4733: the need to use the return stack explicitly. So, if you want to produce
                   4734: a standard compliant program and you are using local variables in a
                   4735: word, forget about return stack manipulations in that word (refer to the
                   4736: standard document for the exact rules).
                   4737: 
1.1       anton    4738: doc->r
                   4739: doc-r>
                   4740: doc-r@
                   4741: doc-rdrop
                   4742: doc-2>r
                   4743: doc-2r>
                   4744: doc-2r@
                   4745: doc-2rdrop
                   4746: 
1.44      crook    4747: 
1.1       anton    4748: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4749: @subsection Locals stack
                   4750: 
1.78      anton    4751: Gforth uses an extra locals stack.  It is described, along with the
                   4752: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4753: 
1.1       anton    4754: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4755: @subsection Stack pointer manipulation
                   4756: @cindex stack pointer manipulation words
                   4757: 
1.44      crook    4758: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4759: doc-sp0
1.1       anton    4760: doc-sp@
                   4761: doc-sp!
1.21      crook    4762: doc-fp0
1.1       anton    4763: doc-fp@
                   4764: doc-fp!
1.21      crook    4765: doc-rp0
1.1       anton    4766: doc-rp@
                   4767: doc-rp!
1.21      crook    4768: doc-lp0
1.1       anton    4769: doc-lp@
                   4770: doc-lp!
                   4771: 
1.44      crook    4772: 
1.1       anton    4773: @node Memory, Control Structures, Stack Manipulation, Words
                   4774: @section Memory
1.26      crook    4775: @cindex memory words
1.1       anton    4776: 
1.32      anton    4777: @menu
                   4778: * Memory model::                
                   4779: * Dictionary allocation::       
                   4780: * Heap Allocation::             
                   4781: * Memory Access::               
                   4782: * Address arithmetic::          
                   4783: * Memory Blocks::               
                   4784: @end menu
                   4785: 
1.67      anton    4786: In addition to the standard Forth memory allocation words, there is also
                   4787: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   4788: garbage collector}.
                   4789: 
1.32      anton    4790: @node Memory model, Dictionary allocation, Memory, Memory
                   4791: @subsection ANS Forth and Gforth memory models
                   4792: 
                   4793: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4794: @c the dictionary?), so let's not stick to closely with it.
                   4795: 
1.67      anton    4796: ANS Forth considers a Forth system as consisting of several address
                   4797: spaces, of which only @dfn{data space} is managed and accessible with
                   4798: the memory words.  Memory not necessarily in data space includes the
                   4799: stacks, the code (called code space) and the headers (called name
                   4800: space). In Gforth everything is in data space, but the code for the
                   4801: primitives is usually read-only.
1.32      anton    4802: 
                   4803: Data space is divided into a number of areas: The (data space portion of
                   4804: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   4805: refer to the search data structure embodied in word lists and headers,
                   4806: because it is used for looking up names, just as you would in a
                   4807: conventional dictionary.}, the heap, and a number of system-allocated
                   4808: buffers.
                   4809: 
1.68      anton    4810: @cindex address arithmetic restrictions, ANS vs. Gforth
                   4811: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    4812: In ANS Forth data space is also divided into contiguous regions.  You
                   4813: can only use address arithmetic within a contiguous region, not between
                   4814: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    4815: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    4816: allocation}).
                   4817: 
                   4818: Gforth provides one big address space, and address arithmetic can be
                   4819: performed between any addresses. However, in the dictionary headers or
                   4820: code are interleaved with data, so almost the only contiguous data space
                   4821: regions there are those described by ANS Forth as contiguous; but you
                   4822: can be sure that the dictionary is allocated towards increasing
                   4823: addresses even between contiguous regions.  The memory order of
                   4824: allocations in the heap is platform-dependent (and possibly different
                   4825: from one run to the next).
                   4826: 
1.27      crook    4827: 
1.32      anton    4828: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   4829: @subsection Dictionary allocation
1.27      crook    4830: @cindex reserving data space
                   4831: @cindex data space - reserving some
                   4832: 
1.32      anton    4833: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   4834: you want to deallocate X, you also deallocate everything
                   4835: allocated after X.
                   4836: 
1.68      anton    4837: @cindex contiguous regions in dictionary allocation
1.32      anton    4838: The allocations using the words below are contiguous and grow the region
                   4839: towards increasing addresses.  Other words that allocate dictionary
                   4840: memory of any kind (i.e., defining words including @code{:noname}) end
                   4841: the contiguous region and start a new one.
                   4842: 
                   4843: In ANS Forth only @code{create}d words are guaranteed to produce an
                   4844: address that is the start of the following contiguous region.  In
                   4845: particular, the cell allocated by @code{variable} is not guaranteed to
                   4846: be contiguous with following @code{allot}ed memory.
                   4847: 
                   4848: You can deallocate memory by using @code{allot} with a negative argument
                   4849: (with some restrictions, see @code{allot}). For larger deallocations use
                   4850: @code{marker}.
1.27      crook    4851: 
1.29      crook    4852: 
1.27      crook    4853: doc-here
                   4854: doc-unused
                   4855: doc-allot
                   4856: doc-c,
1.29      crook    4857: doc-f,
1.27      crook    4858: doc-,
                   4859: doc-2,
                   4860: 
1.32      anton    4861: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   4862: course you should allocate memory in an aligned way, too. I.e., before
                   4863: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   4864: The words below align @code{here} if it is not already.  Basically it is
                   4865: only already aligned for a type, if the last allocation was a multiple
                   4866: of the size of this type and if @code{here} was aligned for this type
                   4867: before.
                   4868: 
                   4869: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   4870: ANS Forth (@code{maxalign}ed in Gforth).
                   4871: 
                   4872: doc-align
                   4873: doc-falign
                   4874: doc-sfalign
                   4875: doc-dfalign
                   4876: doc-maxalign
                   4877: doc-cfalign
                   4878: 
                   4879: 
                   4880: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   4881: @subsection Heap allocation
                   4882: @cindex heap allocation
                   4883: @cindex dynamic allocation of memory
                   4884: @cindex memory-allocation word set
                   4885: 
1.68      anton    4886: @cindex contiguous regions and heap allocation
1.32      anton    4887: Heap allocation supports deallocation of allocated memory in any
                   4888: order. Dictionary allocation is not affected by it (i.e., it does not
                   4889: end a contiguous region). In Gforth, these words are implemented using
                   4890: the standard C library calls malloc(), free() and resize().
                   4891: 
1.68      anton    4892: The memory region produced by one invocation of @code{allocate} or
                   4893: @code{resize} is internally contiguous.  There is no contiguity between
                   4894: such a region and any other region (including others allocated from the
                   4895: heap).
                   4896: 
1.32      anton    4897: doc-allocate
                   4898: doc-free
                   4899: doc-resize
                   4900: 
1.27      crook    4901: 
1.32      anton    4902: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    4903: @subsection Memory Access
                   4904: @cindex memory access words
                   4905: 
                   4906: doc-@
                   4907: doc-!
                   4908: doc-+!
                   4909: doc-c@
                   4910: doc-c!
                   4911: doc-2@
                   4912: doc-2!
                   4913: doc-f@
                   4914: doc-f!
                   4915: doc-sf@
                   4916: doc-sf!
                   4917: doc-df@
                   4918: doc-df!
                   4919: 
1.68      anton    4920: 
1.32      anton    4921: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   4922: @subsection Address arithmetic
1.1       anton    4923: @cindex address arithmetic words
                   4924: 
1.67      anton    4925: Address arithmetic is the foundation on which you can build data
                   4926: structures like arrays, records (@pxref{Structures}) and objects
                   4927: (@pxref{Object-oriented Forth}).
1.32      anton    4928: 
1.68      anton    4929: @cindex address unit
                   4930: @cindex au (address unit)
1.1       anton    4931: ANS Forth does not specify the sizes of the data types. Instead, it
                   4932: offers a number of words for computing sizes and doing address
1.29      crook    4933: arithmetic. Address arithmetic is performed in terms of address units
                   4934: (aus); on most systems the address unit is one byte. Note that a
                   4935: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    4936: platforms where it is a noop, it compiles to nothing).
1.1       anton    4937: 
1.67      anton    4938: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   4939: you have the address of a cell, perform @code{1 cells +}, and you will
                   4940: have the address of the next cell.
                   4941: 
1.68      anton    4942: @cindex contiguous regions and address arithmetic
1.67      anton    4943: In ANS Forth you can perform address arithmetic only within a contiguous
                   4944: region, i.e., if you have an address into one region, you can only add
                   4945: and subtract such that the result is still within the region; you can
                   4946: only subtract or compare addresses from within the same contiguous
                   4947: region.  Reasons: several contiguous regions can be arranged in memory
                   4948: in any way; on segmented systems addresses may have unusual
                   4949: representations, such that address arithmetic only works within a
                   4950: region.  Gforth provides a few more guarantees (linear address space,
                   4951: dictionary grows upwards), but in general I have found it easy to stay
                   4952: within contiguous regions (exception: computing and comparing to the
                   4953: address just beyond the end of an array).
                   4954: 
1.1       anton    4955: @cindex alignment of addresses for types
                   4956: ANS Forth also defines words for aligning addresses for specific
                   4957: types. Many computers require that accesses to specific data types
                   4958: must only occur at specific addresses; e.g., that cells may only be
                   4959: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   4960: accesses, it can usually perform aligned accesses faster. 
                   4961: 
                   4962: For the performance-conscious: alignment operations are usually only
                   4963: necessary during the definition of a data structure, not during the
                   4964: (more frequent) accesses to it.
                   4965: 
                   4966: ANS Forth defines no words for character-aligning addresses. This is not
                   4967: an oversight, but reflects the fact that addresses that are not
                   4968: char-aligned have no use in the standard and therefore will not be
                   4969: created.
                   4970: 
                   4971: @cindex @code{CREATE} and alignment
1.29      crook    4972: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    4973: are cell-aligned; in addition, Gforth guarantees that these addresses
                   4974: are aligned for all purposes.
                   4975: 
1.26      crook    4976: Note that the ANS Forth word @code{char} has nothing to do with address
                   4977: arithmetic.
1.1       anton    4978: 
1.44      crook    4979: 
1.1       anton    4980: doc-chars
                   4981: doc-char+
                   4982: doc-cells
                   4983: doc-cell+
                   4984: doc-cell
                   4985: doc-aligned
                   4986: doc-floats
                   4987: doc-float+
                   4988: doc-float
                   4989: doc-faligned
                   4990: doc-sfloats
                   4991: doc-sfloat+
                   4992: doc-sfaligned
                   4993: doc-dfloats
                   4994: doc-dfloat+
                   4995: doc-dfaligned
                   4996: doc-maxaligned
                   4997: doc-cfaligned
                   4998: doc-address-unit-bits
                   4999: 
1.44      crook    5000: 
1.32      anton    5001: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5002: @subsection Memory Blocks
                   5003: @cindex memory block words
1.27      crook    5004: @cindex character strings - moving and copying
                   5005: 
1.49      anton    5006: Memory blocks often represent character strings; For ways of storing
                   5007: character strings in memory see @ref{String Formats}.  For other
                   5008: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5009: 
1.67      anton    5010: A few of these words work on address unit blocks.  In that case, you
                   5011: usually have to insert @code{CHARS} before the word when working on
                   5012: character strings.  Most words work on character blocks, and expect a
                   5013: char-aligned address.
                   5014: 
                   5015: When copying characters between overlapping memory regions, use
                   5016: @code{chars move} or choose carefully between @code{cmove} and
                   5017: @code{cmove>}.
1.44      crook    5018: 
1.1       anton    5019: doc-move
                   5020: doc-erase
                   5021: doc-cmove
                   5022: doc-cmove>
                   5023: doc-fill
                   5024: doc-blank
1.21      crook    5025: doc-compare
1.111     anton    5026: doc-str=
                   5027: doc-str<
                   5028: doc-string-prefix?
1.21      crook    5029: doc-search
1.27      crook    5030: doc--trailing
                   5031: doc-/string
1.82      anton    5032: doc-bounds
1.44      crook    5033: 
1.111     anton    5034: 
1.27      crook    5035: @comment TODO examples
                   5036: 
1.1       anton    5037: 
1.26      crook    5038: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5039: @section Control Structures
                   5040: @cindex control structures
                   5041: 
1.33      anton    5042: Control structures in Forth cannot be used interpretively, only in a
                   5043: colon definition@footnote{To be precise, they have no interpretation
                   5044: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5045: not like this limitation, but have not seen a satisfying way around it
                   5046: yet, although many schemes have been proposed.
1.1       anton    5047: 
                   5048: @menu
1.33      anton    5049: * Selection::                   IF ... ELSE ... ENDIF
                   5050: * Simple Loops::                BEGIN ...
1.29      crook    5051: * Counted Loops::               DO
1.67      anton    5052: * Arbitrary control structures::  
                   5053: * Calls and returns::           
1.1       anton    5054: * Exception Handling::          
                   5055: @end menu
                   5056: 
                   5057: @node Selection, Simple Loops, Control Structures, Control Structures
                   5058: @subsection Selection
                   5059: @cindex selection control structures
                   5060: @cindex control structures for selection
                   5061: 
                   5062: @cindex @code{IF} control structure
                   5063: @example
1.29      crook    5064: @i{flag}
1.1       anton    5065: IF
1.29      crook    5066:   @i{code}
1.1       anton    5067: ENDIF
                   5068: @end example
1.21      crook    5069: @noindent
1.33      anton    5070: 
1.44      crook    5071: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5072: with any bit set represents truth) @i{code} is executed.
1.33      anton    5073: 
1.1       anton    5074: @example
1.29      crook    5075: @i{flag}
1.1       anton    5076: IF
1.29      crook    5077:   @i{code1}
1.1       anton    5078: ELSE
1.29      crook    5079:   @i{code2}
1.1       anton    5080: ENDIF
                   5081: @end example
                   5082: 
1.44      crook    5083: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5084: executed.
1.33      anton    5085: 
1.1       anton    5086: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5087: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5088: recommend using @code{ENDIF}, because it is less confusing for people
                   5089: who also know other languages (and is not prone to reinforcing negative
                   5090: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5091: system that only supplies @code{THEN} is simple:
                   5092: @example
1.82      anton    5093: : ENDIF   POSTPONE then ; immediate
1.1       anton    5094: @end example
                   5095: 
                   5096: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5097: (adv.)}  has the following meanings:
                   5098: @quotation
                   5099: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5100: (if you were there, then you saw them).
                   5101: @end quotation
                   5102: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5103: and many other programming languages has the meaning 3d.]
                   5104: 
1.21      crook    5105: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5106: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5107: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5108: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5109: @file{compat/control.fs}.
                   5110: 
                   5111: @cindex @code{CASE} control structure
                   5112: @example
1.29      crook    5113: @i{n}
1.1       anton    5114: CASE
1.29      crook    5115:   @i{n1} OF @i{code1} ENDOF
                   5116:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5117:   @dots{}
1.68      anton    5118:   ( n ) @i{default-code} ( n )
1.1       anton    5119: ENDCASE
                   5120: @end example
                   5121: 
1.68      anton    5122: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
                   5123: @i{ni} matches, the optional @i{default-code} is executed. The optional
                   5124: default case can be added by simply writing the code after the last
                   5125: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
                   5126: not consume it.
1.1       anton    5127: 
1.69      anton    5128: @progstyle
                   5129: To keep the code understandable, you should ensure that on all paths
                   5130: through a selection construct the stack is changed in the same way
                   5131: (wrt. number and types of stack items consumed and pushed).
                   5132: 
1.1       anton    5133: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5134: @subsection Simple Loops
                   5135: @cindex simple loops
                   5136: @cindex loops without count 
                   5137: 
                   5138: @cindex @code{WHILE} loop
                   5139: @example
                   5140: BEGIN
1.29      crook    5141:   @i{code1}
                   5142:   @i{flag}
1.1       anton    5143: WHILE
1.29      crook    5144:   @i{code2}
1.1       anton    5145: REPEAT
                   5146: @end example
                   5147: 
1.29      crook    5148: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5149: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5150: false, execution continues after the @code{REPEAT}.
                   5151: 
                   5152: @cindex @code{UNTIL} loop
                   5153: @example
                   5154: BEGIN
1.29      crook    5155:   @i{code}
                   5156:   @i{flag}
1.1       anton    5157: UNTIL
                   5158: @end example
                   5159: 
1.29      crook    5160: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5161: 
1.69      anton    5162: @progstyle
                   5163: To keep the code understandable, a complete iteration of the loop should
                   5164: not change the number and types of the items on the stacks.
                   5165: 
1.1       anton    5166: @cindex endless loop
                   5167: @cindex loops, endless
                   5168: @example
                   5169: BEGIN
1.29      crook    5170:   @i{code}
1.1       anton    5171: AGAIN
                   5172: @end example
                   5173: 
                   5174: This is an endless loop.
                   5175: 
                   5176: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5177: @subsection Counted Loops
                   5178: @cindex counted loops
                   5179: @cindex loops, counted
                   5180: @cindex @code{DO} loops
                   5181: 
                   5182: The basic counted loop is:
                   5183: @example
1.29      crook    5184: @i{limit} @i{start}
1.1       anton    5185: ?DO
1.29      crook    5186:   @i{body}
1.1       anton    5187: LOOP
                   5188: @end example
                   5189: 
1.29      crook    5190: This performs one iteration for every integer, starting from @i{start}
                   5191: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5192: accessed with @code{i}. For example, the loop:
1.1       anton    5193: @example
                   5194: 10 0 ?DO
                   5195:   i .
                   5196: LOOP
                   5197: @end example
1.21      crook    5198: @noindent
                   5199: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5200: 
1.1       anton    5201: The index of the innermost loop can be accessed with @code{i}, the index
                   5202: of the next loop with @code{j}, and the index of the third loop with
                   5203: @code{k}.
                   5204: 
1.44      crook    5205: 
1.1       anton    5206: doc-i
                   5207: doc-j
                   5208: doc-k
                   5209: 
1.44      crook    5210: 
1.1       anton    5211: The loop control data are kept on the return stack, so there are some
1.21      crook    5212: restrictions on mixing return stack accesses and counted loop words. In
                   5213: particuler, if you put values on the return stack outside the loop, you
                   5214: cannot read them inside the loop@footnote{well, not in a way that is
                   5215: portable.}. If you put values on the return stack within a loop, you
                   5216: have to remove them before the end of the loop and before accessing the
                   5217: index of the loop.
1.1       anton    5218: 
                   5219: There are several variations on the counted loop:
                   5220: 
1.21      crook    5221: @itemize @bullet
                   5222: @item
                   5223: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5224: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5225: 
                   5226: @example
                   5227: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5228: @end example
                   5229: prints @code{0 1 2 3}
                   5230: 
1.1       anton    5231: 
1.21      crook    5232: @item
                   5233: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5234: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5235: return stack so @code{EXIT} can get to its return address. For example:
                   5236: 
                   5237: @example
                   5238: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5239: @end example
                   5240: prints @code{0 1 2 3}
                   5241: 
                   5242: 
                   5243: @item
1.29      crook    5244: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5245: (and @code{LOOP} iterates until they become equal by wrap-around
                   5246: arithmetic). This behaviour is usually not what you want. Therefore,
                   5247: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5248: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5249: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5250: unsigned loop parameters.
                   5251: 
1.21      crook    5252: @item
                   5253: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5254: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5255: if you know that the loop is entered in any case. Such knowledge tends
                   5256: to become invalid during maintenance of a program, and then the
                   5257: @code{DO} will make trouble.
                   5258: 
                   5259: @item
1.29      crook    5260: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5261: index by @i{n} instead of by 1. The loop is terminated when the border
                   5262: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5263: 
1.21      crook    5264: @example
                   5265: 4 0 +DO  i .  2 +LOOP
                   5266: @end example
                   5267: @noindent
                   5268: prints @code{0 2}
                   5269: 
                   5270: @example
                   5271: 4 1 +DO  i .  2 +LOOP
                   5272: @end example
                   5273: @noindent
                   5274: prints @code{1 3}
1.1       anton    5275: 
1.68      anton    5276: @item
1.1       anton    5277: @cindex negative increment for counted loops
                   5278: @cindex counted loops with negative increment
1.29      crook    5279: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5280: 
1.21      crook    5281: @example
                   5282: -1 0 ?DO  i .  -1 +LOOP
                   5283: @end example
                   5284: @noindent
                   5285: prints @code{0 -1}
1.1       anton    5286: 
1.21      crook    5287: @example
                   5288: 0 0 ?DO  i .  -1 +LOOP
                   5289: @end example
                   5290: prints nothing.
1.1       anton    5291: 
1.29      crook    5292: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5293: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5294: index by @i{u} each iteration. The loop is terminated when the border
                   5295: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5296: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5297: 
1.21      crook    5298: @example
                   5299: -2 0 -DO  i .  1 -LOOP
                   5300: @end example
                   5301: @noindent
                   5302: prints @code{0 -1}
1.1       anton    5303: 
1.21      crook    5304: @example
                   5305: -1 0 -DO  i .  1 -LOOP
                   5306: @end example
                   5307: @noindent
                   5308: prints @code{0}
                   5309: 
                   5310: @example
                   5311: 0 0 -DO  i .  1 -LOOP
                   5312: @end example
                   5313: @noindent
                   5314: prints nothing.
1.1       anton    5315: 
1.21      crook    5316: @end itemize
1.1       anton    5317: 
                   5318: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5319: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5320: for these words that uses only standard words is provided in
                   5321: @file{compat/loops.fs}.
1.1       anton    5322: 
                   5323: 
                   5324: @cindex @code{FOR} loops
1.26      crook    5325: Another counted loop is:
1.1       anton    5326: @example
1.29      crook    5327: @i{n}
1.1       anton    5328: FOR
1.29      crook    5329:   @i{body}
1.1       anton    5330: NEXT
                   5331: @end example
                   5332: This is the preferred loop of native code compiler writers who are too
1.26      crook    5333: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5334: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5335: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5336: Forth systems may behave differently, even if they support @code{FOR}
                   5337: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5338: 
                   5339: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5340: @subsection Arbitrary control structures
                   5341: @cindex control structures, user-defined
                   5342: 
                   5343: @cindex control-flow stack
                   5344: ANS Forth permits and supports using control structures in a non-nested
                   5345: way. Information about incomplete control structures is stored on the
                   5346: control-flow stack. This stack may be implemented on the Forth data
                   5347: stack, and this is what we have done in Gforth.
                   5348: 
                   5349: @cindex @code{orig}, control-flow stack item
                   5350: @cindex @code{dest}, control-flow stack item
                   5351: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5352: entry represents a backward branch target. A few words are the basis for
                   5353: building any control structure possible (except control structures that
                   5354: need storage, like calls, coroutines, and backtracking).
                   5355: 
1.44      crook    5356: 
1.1       anton    5357: doc-if
                   5358: doc-ahead
                   5359: doc-then
                   5360: doc-begin
                   5361: doc-until
                   5362: doc-again
                   5363: doc-cs-pick
                   5364: doc-cs-roll
                   5365: 
1.44      crook    5366: 
1.21      crook    5367: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5368: manipulate the control-flow stack in a portable way. Without them, you
                   5369: would need to know how many stack items are occupied by a control-flow
                   5370: entry (many systems use one cell. In Gforth they currently take three,
                   5371: but this may change in the future).
                   5372: 
1.1       anton    5373: Some standard control structure words are built from these words:
                   5374: 
1.44      crook    5375: 
1.1       anton    5376: doc-else
                   5377: doc-while
                   5378: doc-repeat
                   5379: 
1.44      crook    5380: 
                   5381: @noindent
1.1       anton    5382: Gforth adds some more control-structure words:
                   5383: 
1.44      crook    5384: 
1.1       anton    5385: doc-endif
                   5386: doc-?dup-if
                   5387: doc-?dup-0=-if
                   5388: 
1.44      crook    5389: 
                   5390: @noindent
1.1       anton    5391: Counted loop words constitute a separate group of words:
                   5392: 
1.44      crook    5393: 
1.1       anton    5394: doc-?do
                   5395: doc-+do
                   5396: doc-u+do
                   5397: doc--do
                   5398: doc-u-do
                   5399: doc-do
                   5400: doc-for
                   5401: doc-loop
                   5402: doc-+loop
                   5403: doc--loop
                   5404: doc-next
                   5405: doc-leave
                   5406: doc-?leave
                   5407: doc-unloop
                   5408: doc-done
                   5409: 
1.44      crook    5410: 
1.21      crook    5411: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5412: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5413: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5414: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5415: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5416: resolved (by using one of the loop-ending words or @code{DONE}).
                   5417: 
1.44      crook    5418: @noindent
1.26      crook    5419: Another group of control structure words are:
1.1       anton    5420: 
1.44      crook    5421: 
1.1       anton    5422: doc-case
                   5423: doc-endcase
                   5424: doc-of
                   5425: doc-endof
                   5426: 
1.44      crook    5427: 
1.21      crook    5428: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5429: @code{CS-ROLL}.
1.1       anton    5430: 
                   5431: @subsubsection Programming Style
1.47      crook    5432: @cindex control structures programming style
                   5433: @cindex programming style, arbitrary control structures
1.1       anton    5434: 
                   5435: In order to ensure readability we recommend that you do not create
                   5436: arbitrary control structures directly, but define new control structure
                   5437: words for the control structure you want and use these words in your
1.26      crook    5438: program. For example, instead of writing:
1.1       anton    5439: 
                   5440: @example
1.26      crook    5441: BEGIN
1.1       anton    5442:   ...
1.26      crook    5443: IF [ 1 CS-ROLL ]
1.1       anton    5444:   ...
1.26      crook    5445: AGAIN THEN
1.1       anton    5446: @end example
                   5447: 
1.21      crook    5448: @noindent
1.1       anton    5449: we recommend defining control structure words, e.g.,
                   5450: 
                   5451: @example
1.26      crook    5452: : WHILE ( DEST -- ORIG DEST )
                   5453:  POSTPONE IF
                   5454:  1 CS-ROLL ; immediate
                   5455: 
                   5456: : REPEAT ( orig dest -- )
                   5457:  POSTPONE AGAIN
                   5458:  POSTPONE THEN ; immediate
1.1       anton    5459: @end example
                   5460: 
1.21      crook    5461: @noindent
1.1       anton    5462: and then using these to create the control structure:
                   5463: 
                   5464: @example
1.26      crook    5465: BEGIN
1.1       anton    5466:   ...
1.26      crook    5467: WHILE
1.1       anton    5468:   ...
1.26      crook    5469: REPEAT
1.1       anton    5470: @end example
                   5471: 
                   5472: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5473: @code{WHILE} are predefined, so in this example it would not be
                   5474: necessary to define them.
                   5475: 
                   5476: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5477: @subsection Calls and returns
                   5478: @cindex calling a definition
                   5479: @cindex returning from a definition
                   5480: 
1.3       anton    5481: @cindex recursive definitions
                   5482: A definition can be called simply be writing the name of the definition
1.26      crook    5483: to be called. Normally a definition is invisible during its own
1.3       anton    5484: definition. If you want to write a directly recursive definition, you
1.26      crook    5485: can use @code{recursive} to make the current definition visible, or
                   5486: @code{recurse} to call the current definition directly.
1.3       anton    5487: 
1.44      crook    5488: 
1.3       anton    5489: doc-recursive
                   5490: doc-recurse
                   5491: 
1.44      crook    5492: 
1.21      crook    5493: @comment TODO add example of the two recursion methods
1.12      anton    5494: @quotation
                   5495: @progstyle
                   5496: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5497: definition by name is more descriptive (if the name is well-chosen) than
                   5498: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5499: implementation, it is much better to read (and think) ``now sort the
                   5500: partitions'' than to read ``now do a recursive call''.
                   5501: @end quotation
1.3       anton    5502: 
1.29      crook    5503: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5504: 
                   5505: @example
1.28      crook    5506: Defer foo
1.3       anton    5507: 
                   5508: : bar ( ... -- ... )
                   5509:  ... foo ... ;
                   5510: 
                   5511: :noname ( ... -- ... )
                   5512:  ... bar ... ;
                   5513: IS foo
                   5514: @end example
                   5515: 
1.44      crook    5516: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33      anton    5517: 
1.26      crook    5518: The current definition returns control to the calling definition when
1.33      anton    5519: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5520: 
                   5521: doc-exit
                   5522: doc-;s
                   5523: 
1.44      crook    5524: 
1.1       anton    5525: @node Exception Handling,  , Calls and returns, Control Structures
                   5526: @subsection Exception Handling
1.26      crook    5527: @cindex exceptions
1.1       anton    5528: 
1.68      anton    5529: @c quit is a very bad idea for error handling, 
                   5530: @c because it does not translate into a THROW
                   5531: @c it also does not belong into this chapter
                   5532: 
                   5533: If a word detects an error condition that it cannot handle, it can
                   5534: @code{throw} an exception.  In the simplest case, this will terminate
                   5535: your program, and report an appropriate error.
1.21      crook    5536: 
1.68      anton    5537: doc-throw
1.1       anton    5538: 
1.69      anton    5539: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5540: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5541: Gforth (and most other systems) you can use the iors produced by various
                   5542: words as error numbers (e.g., a typical use of @code{allocate} is
                   5543: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5544: to define your own error numbers (with decent error reporting); an ANS
                   5545: Forth version of this word (but without the error messages) is available
                   5546: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5547: numbers (anything outside the range -4095..0), but won't get nice error
                   5548: messages, only numbers.  For example, try:
                   5549: 
                   5550: @example
1.69      anton    5551: -10 throw                    \ ANS defined
                   5552: -267 throw                   \ system defined
                   5553: s" my error" exception throw \ user defined
                   5554: 7 throw                      \ arbitrary number
1.68      anton    5555: @end example
                   5556: 
                   5557: doc---exception-exception
1.1       anton    5558: 
1.69      anton    5559: A common idiom to @code{THROW} a specific error if a flag is true is
                   5560: this:
                   5561: 
                   5562: @example
                   5563: @code{( flag ) 0<> @i{errno} and throw}
                   5564: @end example
                   5565: 
                   5566: Your program can provide exception handlers to catch exceptions.  An
                   5567: exception handler can be used to correct the problem, or to clean up
                   5568: some data structures and just throw the exception to the next exception
                   5569: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5570: exception handler.  The system's exception handler is outermost, and just
                   5571: prints an error and restarts command-line interpretation (or, in batch
                   5572: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5573: 
1.68      anton    5574: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5575: 
1.68      anton    5576: doc-catch
                   5577: 
                   5578: The most common use of exception handlers is to clean up the state when
                   5579: an error happens.  E.g.,
1.1       anton    5580: 
1.26      crook    5581: @example
1.68      anton    5582: base @ >r hex \ actually the hex should be inside foo, or we h
                   5583: ['] foo catch ( nerror|0 )
                   5584: r> base !
1.69      anton    5585: ( nerror|0 ) throw \ pass it on
1.26      crook    5586: @end example
1.1       anton    5587: 
1.69      anton    5588: A use of @code{catch} for handling the error @code{myerror} might look
                   5589: like this:
1.44      crook    5590: 
1.68      anton    5591: @example
1.69      anton    5592: ['] foo catch
                   5593: CASE
                   5594:   myerror OF ... ( do something about it ) ENDOF
                   5595:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5596: ENDCASE
1.68      anton    5597: @end example
1.44      crook    5598: 
1.68      anton    5599: Having to wrap the code into a separate word is often cumbersome,
                   5600: therefore Gforth provides an alternative syntax:
1.1       anton    5601: 
                   5602: @example
1.69      anton    5603: TRY
1.68      anton    5604:   @i{code1}
1.69      anton    5605: RECOVER     \ optional
1.68      anton    5606:   @i{code2} \ optional
1.69      anton    5607: ENDTRY
1.1       anton    5608: @end example
                   5609: 
1.68      anton    5610: This performs @i{Code1}.  If @i{code1} completes normally, execution
                   5611: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
                   5612: reset to the state during @code{try}, the throw value is pushed on the
                   5613: data stack, and execution constinues at @i{code2}, and finally falls
1.92      anton    5614: through the @code{endtry} into the following code.
1.26      crook    5615: 
1.68      anton    5616: doc-try
                   5617: doc-recover
                   5618: doc-endtry
1.26      crook    5619: 
1.69      anton    5620: The cleanup example from above in this syntax:
1.26      crook    5621: 
1.68      anton    5622: @example
1.69      anton    5623: base @ >r TRY
1.68      anton    5624:   hex foo \ now the hex is placed correctly
1.69      anton    5625:   0       \ value for throw
1.92      anton    5626: RECOVER ENDTRY
1.68      anton    5627: r> base ! throw
1.1       anton    5628: @end example
                   5629: 
1.69      anton    5630: And here's the error handling example:
1.1       anton    5631: 
1.68      anton    5632: @example
1.69      anton    5633: TRY
1.68      anton    5634:   foo
1.69      anton    5635: RECOVER
                   5636:   CASE
                   5637:     myerror OF ... ( do something about it ) ENDOF
                   5638:     throw \ pass other errors on
                   5639:   ENDCASE
                   5640: ENDTRY
1.68      anton    5641: @end example
1.1       anton    5642: 
1.69      anton    5643: @progstyle
                   5644: As usual, you should ensure that the stack depth is statically known at
                   5645: the end: either after the @code{throw} for passing on errors, or after
                   5646: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5647: selection construct for handling the error).
                   5648: 
1.68      anton    5649: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5650: and you can provide an error message.  @code{Abort} just produces an
                   5651: ``Aborted'' error.
1.1       anton    5652: 
1.68      anton    5653: The problem with these words is that exception handlers cannot
                   5654: differentiate between different @code{abort"}s; they just look like
                   5655: @code{-2 throw} to them (the error message cannot be accessed by
                   5656: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5657: exception handlers.
1.44      crook    5658: 
1.68      anton    5659: doc-abort"
1.26      crook    5660: doc-abort
1.29      crook    5661: 
                   5662: 
1.44      crook    5663: 
1.29      crook    5664: @c -------------------------------------------------------------
1.47      crook    5665: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5666: @section Defining Words
                   5667: @cindex defining words
                   5668: 
1.47      crook    5669: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5670: 
1.29      crook    5671: @menu
1.67      anton    5672: * CREATE::                      
1.44      crook    5673: * Variables::                   Variables and user variables
1.67      anton    5674: * Constants::                   
1.44      crook    5675: * Values::                      Initialised variables
1.67      anton    5676: * Colon Definitions::           
1.44      crook    5677: * Anonymous Definitions::       Definitions without names
1.69      anton    5678: * Supplying names::             Passing definition names as strings
1.67      anton    5679: * User-defined Defining Words::  
1.44      crook    5680: * Deferred words::              Allow forward references
1.67      anton    5681: * Aliases::                     
1.29      crook    5682: @end menu
                   5683: 
1.44      crook    5684: @node CREATE, Variables, Defining Words, Defining Words
                   5685: @subsection @code{CREATE}
1.29      crook    5686: @cindex simple defining words
                   5687: @cindex defining words, simple
                   5688: 
                   5689: Defining words are used to create new entries in the dictionary. The
                   5690: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5691: this:
                   5692: 
                   5693: @example
                   5694: CREATE new-word1
                   5695: @end example
                   5696: 
1.69      anton    5697: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   5698: input stream (@code{new-word1} in our example).  It generates a
                   5699: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   5700: executed, all that it does is leave an address on the stack. The address
                   5701: represents the value of the data space pointer (@code{HERE}) at the time
                   5702: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   5703: associating a name with the address of a region of memory.
1.29      crook    5704: 
1.34      anton    5705: doc-create
                   5706: 
1.69      anton    5707: Note that in ANS Forth guarantees only for @code{create} that its body
                   5708: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   5709: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   5710: @code{create}d words can be modified with @code{does>}
                   5711: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   5712: can only be applied to @code{create}d words.
                   5713: 
1.29      crook    5714: By extending this example to reserve some memory in data space, we end
1.69      anton    5715: up with something like a @i{variable}. Here are two different ways to do
                   5716: it:
1.29      crook    5717: 
                   5718: @example
                   5719: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5720: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   5721: @end example
                   5722: 
                   5723: The variable can be examined and modified using @code{@@} (``fetch'') and
                   5724: @code{!} (``store'') like this:
                   5725: 
                   5726: @example
                   5727: new-word2 @@ .      \ get address, fetch from it and display
                   5728: 1234 new-word2 !   \ new value, get address, store to it
                   5729: @end example
                   5730: 
1.44      crook    5731: @cindex arrays
                   5732: A similar mechanism can be used to create arrays. For example, an
                   5733: 80-character text input buffer:
1.29      crook    5734: 
                   5735: @example
1.44      crook    5736: CREATE text-buf 80 chars allot
                   5737: 
                   5738: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   5739: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   5740: @end example
1.29      crook    5741: 
1.44      crook    5742: You can build arbitrarily complex data structures by allocating
1.49      anton    5743: appropriate areas of memory. For further discussions of this, and to
1.66      anton    5744: learn about some Gforth tools that make it easier,
1.49      anton    5745: @xref{Structures}.
1.44      crook    5746: 
                   5747: 
                   5748: @node Variables, Constants, CREATE, Defining Words
                   5749: @subsection Variables
                   5750: @cindex variables
                   5751: 
                   5752: The previous section showed how a sequence of commands could be used to
                   5753: generate a variable.  As a final refinement, the whole code sequence can
                   5754: be wrapped up in a defining word (pre-empting the subject of the next
                   5755: section), making it easier to create new variables:
                   5756: 
                   5757: @example
                   5758: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   5759: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   5760: 
                   5761: myvariableX foo \ variable foo starts off with an unknown value
                   5762: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    5763: 
                   5764: 45 3 * foo !   \ set foo to 135
                   5765: 1234 joe !     \ set joe to 1234
                   5766: 3 joe +!       \ increment joe by 3.. to 1237
                   5767: @end example
                   5768: 
                   5769: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    5770: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    5771: guarantee that a @code{Variable} is initialised when it is created
                   5772: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   5773: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   5774: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    5775: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    5776: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    5777: store a boolean, you can use @code{on} and @code{off} to toggle its
                   5778: state.
1.29      crook    5779: 
1.34      anton    5780: doc-variable
                   5781: doc-2variable
                   5782: doc-fvariable
                   5783: 
1.29      crook    5784: @cindex user variables
                   5785: @cindex user space
                   5786: The defining word @code{User} behaves in the same way as @code{Variable}.
                   5787: The difference is that it reserves space in @i{user (data) space} rather
                   5788: than normal data space. In a Forth system that has a multi-tasker, each
                   5789: task has its own set of user variables.
                   5790: 
1.34      anton    5791: doc-user
1.67      anton    5792: @c doc-udp
                   5793: @c doc-uallot
1.34      anton    5794: 
1.29      crook    5795: @comment TODO is that stuff about user variables strictly correct? Is it
                   5796: @comment just terminal tasks that have user variables?
                   5797: @comment should document tasker.fs (with some examples) elsewhere
                   5798: @comment in this manual, then expand on user space and user variables.
                   5799: 
1.44      crook    5800: @node Constants, Values, Variables, Defining Words
                   5801: @subsection Constants
                   5802: @cindex constants
                   5803: 
                   5804: @code{Constant} allows you to declare a fixed value and refer to it by
                   5805: name. For example:
1.29      crook    5806: 
                   5807: @example
                   5808: 12 Constant INCHES-PER-FOOT
                   5809: 3E+08 fconstant SPEED-O-LIGHT
                   5810: @end example
                   5811: 
                   5812: A @code{Variable} can be both read and written, so its run-time
                   5813: behaviour is to supply an address through which its current value can be
                   5814: manipulated. In contrast, the value of a @code{Constant} cannot be
                   5815: changed once it has been declared@footnote{Well, often it can be -- but
                   5816: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   5817: on).} so it's not necessary to supply the address -- it is more
                   5818: efficient to return the value of the constant directly. That's exactly
                   5819: what happens; the run-time effect of a constant is to put its value on
1.49      anton    5820: the top of the stack (You can find one
                   5821: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    5822: 
1.69      anton    5823: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    5824: double and floating-point constants, respectively.
                   5825: 
1.34      anton    5826: doc-constant
                   5827: doc-2constant
                   5828: doc-fconstant
                   5829: 
                   5830: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    5831: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   5832: @c constant, use it and then delete the definition of the constant..
1.69      anton    5833: 
                   5834: @c anton->An ANS Forth system can compile a constant to a literal; On
                   5835: @c decompilation you would see only the number, just as if it had been used
                   5836: @c in the first place.  The word will stay, of course, but it will only be
                   5837: @c used by the text interpreter (no run-time duties, except when it is 
                   5838: @c POSTPONEd or somesuch).
                   5839: 
                   5840: @c nac:
1.44      crook    5841: @c I agree that it's rather deep, but IMO it is an important difference
                   5842: @c relative to other programming languages.. often it's annoying: it
                   5843: @c certainly changes my programming style relative to C.
                   5844: 
1.69      anton    5845: @c anton: In what way?
                   5846: 
1.29      crook    5847: Constants in Forth behave differently from their equivalents in other
                   5848: programming languages. In other languages, a constant (such as an EQU in
                   5849: assembler or a #define in C) only exists at compile-time; in the
                   5850: executable program the constant has been translated into an absolute
                   5851: number and, unless you are using a symbolic debugger, it's impossible to
                   5852: know what abstract thing that number represents. In Forth a constant has
1.44      crook    5853: an entry in the header space and remains there after the code that uses
                   5854: it has been defined. In fact, it must remain in the dictionary since it
                   5855: has run-time duties to perform. For example:
1.29      crook    5856: 
                   5857: @example
                   5858: 12 Constant INCHES-PER-FOOT
                   5859: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   5860: @end example
                   5861: 
                   5862: @cindex in-lining of constants
                   5863: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   5864: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   5865: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   5866: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   5867: attempt to optimise constants by in-lining them where they are used. You
                   5868: can force Gforth to in-line a constant like this:
                   5869: 
                   5870: @example
                   5871: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   5872: @end example
                   5873: 
                   5874: If you use @code{see} to decompile @i{this} version of
                   5875: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    5876: longer present. To understand how this works, read
                   5877: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    5878: 
                   5879: In-lining constants in this way might improve execution time
                   5880: fractionally, and can ensure that a constant is now only referenced at
                   5881: compile-time. However, the definition of the constant still remains in
                   5882: the dictionary. Some Forth compilers provide a mechanism for controlling
                   5883: a second dictionary for holding transient words such that this second
                   5884: dictionary can be deleted later in order to recover memory
                   5885: space. However, there is no standard way of doing this.
                   5886: 
                   5887: 
1.44      crook    5888: @node Values, Colon Definitions, Constants, Defining Words
                   5889: @subsection Values
                   5890: @cindex values
1.34      anton    5891: 
1.69      anton    5892: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   5893: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   5894: (not in ANS Forth) you can access (and change) a @code{value} also with
                   5895: @code{>body}.
                   5896: 
                   5897: Here are some
                   5898: examples:
1.29      crook    5899: 
                   5900: @example
1.69      anton    5901: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   5902: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   5903: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   5904: APPLES              \ puts 35 on the top of the stack.
1.29      crook    5905: @end example
                   5906: 
1.44      crook    5907: doc-value
                   5908: doc-to
1.29      crook    5909: 
1.35      anton    5910: 
1.69      anton    5911: 
1.44      crook    5912: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   5913: @subsection Colon Definitions
                   5914: @cindex colon definitions
1.35      anton    5915: 
                   5916: @example
1.44      crook    5917: : name ( ... -- ... )
                   5918:     word1 word2 word3 ;
1.29      crook    5919: @end example
                   5920: 
1.44      crook    5921: @noindent
                   5922: Creates a word called @code{name} that, upon execution, executes
                   5923: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    5924: 
1.49      anton    5925: The explanation above is somewhat superficial. For simple examples of
                   5926: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    5927: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    5928: Compilation Semantics}.
1.29      crook    5929: 
1.44      crook    5930: doc-:
                   5931: doc-;
1.1       anton    5932: 
1.34      anton    5933: 
1.69      anton    5934: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    5935: @subsection Anonymous Definitions
                   5936: @cindex colon definitions
                   5937: @cindex defining words without name
1.34      anton    5938: 
1.44      crook    5939: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   5940: name. You can do this with:
1.1       anton    5941: 
1.44      crook    5942: doc-:noname
1.1       anton    5943: 
1.44      crook    5944: This leaves the execution token for the word on the stack after the
                   5945: closing @code{;}. Here's an example in which a deferred word is
                   5946: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    5947: 
1.29      crook    5948: @example
1.44      crook    5949: Defer deferred
                   5950: :noname ( ... -- ... )
                   5951:   ... ;
                   5952: IS deferred
1.29      crook    5953: @end example
1.26      crook    5954: 
1.44      crook    5955: @noindent
                   5956: Gforth provides an alternative way of doing this, using two separate
                   5957: words:
1.27      crook    5958: 
1.44      crook    5959: doc-noname
                   5960: @cindex execution token of last defined word
                   5961: doc-lastxt
1.1       anton    5962: 
1.44      crook    5963: @noindent
                   5964: The previous example can be rewritten using @code{noname} and
                   5965: @code{lastxt}:
1.1       anton    5966: 
1.26      crook    5967: @example
1.44      crook    5968: Defer deferred
                   5969: noname : ( ... -- ... )
                   5970:   ... ;
                   5971: lastxt IS deferred
1.26      crook    5972: @end example
1.1       anton    5973: 
1.29      crook    5974: @noindent
1.44      crook    5975: @code{noname} works with any defining word, not just @code{:}.
                   5976: 
                   5977: @code{lastxt} also works when the last word was not defined as
1.71      anton    5978: @code{noname}.  It does not work for combined words, though.  It also has
                   5979: the useful property that is is valid as soon as the header for a
                   5980: definition has been built. Thus:
1.44      crook    5981: 
                   5982: @example
                   5983: lastxt . : foo [ lastxt . ] ; ' foo .
                   5984: @end example
1.1       anton    5985: 
1.44      crook    5986: @noindent
                   5987: prints 3 numbers; the last two are the same.
1.26      crook    5988: 
1.69      anton    5989: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   5990: @subsection Supplying the name of a defined word
                   5991: @cindex names for defined words
                   5992: @cindex defining words, name given in a string
                   5993: 
                   5994: By default, a defining word takes the name for the defined word from the
                   5995: input stream. Sometimes you want to supply the name from a string. You
                   5996: can do this with:
                   5997: 
                   5998: doc-nextname
                   5999: 
                   6000: For example:
                   6001: 
                   6002: @example
                   6003: s" foo" nextname create
                   6004: @end example
                   6005: 
                   6006: @noindent
                   6007: is equivalent to:
                   6008: 
                   6009: @example
                   6010: create foo
                   6011: @end example
                   6012: 
                   6013: @noindent
                   6014: @code{nextname} works with any defining word.
                   6015: 
1.1       anton    6016: 
1.69      anton    6017: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26      crook    6018: @subsection User-defined Defining Words
                   6019: @cindex user-defined defining words
                   6020: @cindex defining words, user-defined
1.1       anton    6021: 
1.29      crook    6022: You can create a new defining word by wrapping defining-time code around
                   6023: an existing defining word and putting the sequence in a colon
1.69      anton    6024: definition. 
                   6025: 
                   6026: @c anton: This example is very complex and leads in a quite different
                   6027: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6028: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6029: @c subsection of Defining Words)
                   6030: 
                   6031: For example, suppose that you have a word @code{stats} that
1.29      crook    6032: gathers statistics about colon definitions given the @i{xt} of the
                   6033: definition, and you want every colon definition in your application to
                   6034: make a call to @code{stats}. You can define and use a new version of
                   6035: @code{:} like this:
                   6036: 
                   6037: @example
                   6038: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6039:   ... ;  \ other code
                   6040: 
                   6041: : my: : lastxt postpone literal ['] stats compile, ;
                   6042: 
                   6043: my: foo + - ;
                   6044: @end example
                   6045: 
                   6046: When @code{foo} is defined using @code{my:} these steps occur:
                   6047: 
                   6048: @itemize @bullet
                   6049: @item
                   6050: @code{my:} is executed.
                   6051: @item
                   6052: The @code{:} within the definition (the one between @code{my:} and
                   6053: @code{lastxt}) is executed, and does just what it always does; it parses
                   6054: the input stream for a name, builds a dictionary header for the name
                   6055: @code{foo} and switches @code{state} from interpret to compile.
                   6056: @item
                   6057: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   6058: being defined -- @code{foo} -- onto the stack.
                   6059: @item
                   6060: The code that was produced by @code{postpone literal} is executed; this
                   6061: causes the value on the stack to be compiled as a literal in the code
                   6062: area of @code{foo}.
                   6063: @item
                   6064: The code @code{['] stats} compiles a literal into the definition of
                   6065: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6066: execution token for @code{stats} -- is layed down in the code area of
                   6067: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6068: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6069: in the code area is implementation-dependent. A threaded implementation
                   6070: might spit out the execution token directly whilst another
                   6071: implementation might spit out a native code sequence.}.
                   6072: @item
                   6073: At this point, the execution of @code{my:} is complete, and control
                   6074: returns to the text interpreter. The text interpreter is in compile
                   6075: state, so subsequent text @code{+ -} is compiled into the definition of
                   6076: @code{foo} and the @code{;} terminates the definition as always.
                   6077: @end itemize
                   6078: 
                   6079: You can use @code{see} to decompile a word that was defined using
                   6080: @code{my:} and see how it is different from a normal @code{:}
                   6081: definition. For example:
                   6082: 
                   6083: @example
                   6084: : bar + - ;  \ like foo but using : rather than my:
                   6085: see bar
                   6086: : bar
                   6087:   + - ;
                   6088: see foo
                   6089: : foo
                   6090:   107645672 stats + - ;
                   6091: 
                   6092: \ use ' stats . to show that 107645672 is the xt for stats
                   6093: @end example
                   6094: 
                   6095: You can use techniques like this to make new defining words in terms of
                   6096: @i{any} existing defining word.
1.1       anton    6097: 
                   6098: 
1.29      crook    6099: @cindex defining defining words
1.26      crook    6100: @cindex @code{CREATE} ... @code{DOES>}
                   6101: If you want the words defined with your defining words to behave
                   6102: differently from words defined with standard defining words, you can
                   6103: write your defining word like this:
1.1       anton    6104: 
                   6105: @example
1.26      crook    6106: : def-word ( "name" -- )
1.29      crook    6107:     CREATE @i{code1}
1.26      crook    6108: DOES> ( ... -- ... )
1.29      crook    6109:     @i{code2} ;
1.26      crook    6110: 
                   6111: def-word name
1.1       anton    6112: @end example
                   6113: 
1.29      crook    6114: @cindex child words
                   6115: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6116: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6117: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6118: is not executed at this time. The word @code{name} is sometimes called a
                   6119: @dfn{child} of @code{def-word}.
                   6120: 
                   6121: When you execute @code{name}, the address of the body of @code{name} is
                   6122: put on the data stack and @i{code2} is executed (the address of the body
                   6123: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6124: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6125: default).
                   6126: 
                   6127: @c anton:
                   6128: @c www.dictionary.com says:
                   6129: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6130: @c several generations of absence, usually caused by the chance
                   6131: @c recombination of genes.  2.An individual or a part that exhibits
                   6132: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6133: @c of previous behavior after a period of absence.
                   6134: @c
                   6135: @c Doesn't seem to fit.
1.29      crook    6136: 
1.69      anton    6137: @c @cindex atavism in child words
1.33      anton    6138: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6139: similarly; they all have a common run-time behaviour determined by
                   6140: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6141: body of the child word. The structure of the data is common to all
                   6142: children of @code{def-word}, but the data values are specific -- and
                   6143: private -- to each child word. When a child word is executed, the
                   6144: address of its private data area is passed as a parameter on TOS to be
                   6145: used and manipulated@footnote{It is legitimate both to read and write to
                   6146: this data area.} by @i{code2}.
1.29      crook    6147: 
                   6148: The two fragments of code that make up the defining words act (are
                   6149: executed) at two completely separate times:
1.1       anton    6150: 
1.29      crook    6151: @itemize @bullet
                   6152: @item
                   6153: At @i{define time}, the defining word executes @i{code1} to generate a
                   6154: child word
                   6155: @item
                   6156: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6157: is executed, using parameters (data) that are private and specific to
                   6158: the child word.
                   6159: @end itemize
                   6160: 
1.44      crook    6161: Another way of understanding the behaviour of @code{def-word} and
                   6162: @code{name} is to say that, if you make the following definitions:
1.33      anton    6163: @example
                   6164: : def-word1 ( "name" -- )
                   6165:     CREATE @i{code1} ;
                   6166: 
                   6167: : action1 ( ... -- ... )
                   6168:     @i{code2} ;
                   6169: 
                   6170: def-word1 name1
                   6171: @end example
                   6172: 
1.44      crook    6173: @noindent
                   6174: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6175: 
1.29      crook    6176: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6177: 
1.1       anton    6178: @example
1.29      crook    6179: : CONSTANT ( w "name" -- )
                   6180:     CREATE ,
1.26      crook    6181: DOES> ( -- w )
                   6182:     @@ ;
1.1       anton    6183: @end example
                   6184: 
1.29      crook    6185: @comment There is a beautiful description of how this works and what
                   6186: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6187: @comment commentary on the Counting Fruits problem.
                   6188: 
                   6189: When you create a constant with @code{5 CONSTANT five}, a set of
                   6190: define-time actions take place; first a new word @code{five} is created,
                   6191: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6192: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6193: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6194: no code of its own; it simply contains a data field and a pointer to the
                   6195: code that follows @code{DOES>} in its defining word. That makes words
                   6196: created in this way very compact.
                   6197: 
                   6198: The final example in this section is intended to remind you that space
                   6199: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6200: both read and written by a Standard program@footnote{Exercise: use this
                   6201: example as a starting point for your own implementation of @code{Value}
                   6202: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6203: @code{[']}.}:
                   6204: 
                   6205: @example
                   6206: : foo ( "name" -- )
                   6207:     CREATE -1 ,
                   6208: DOES> ( -- )
1.33      anton    6209:     @@ . ;
1.29      crook    6210: 
                   6211: foo first-word
                   6212: foo second-word
                   6213: 
                   6214: 123 ' first-word >BODY !
                   6215: @end example
                   6216: 
                   6217: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6218: have executed it to get the address of its data field. However, since it
                   6219: was defined to have @code{DOES>} actions, its execution semantics are to
                   6220: perform those @code{DOES>} actions. To get the address of its data field
                   6221: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6222: translate the xt into the address of the data field.  When you execute
                   6223: @code{first-word}, it will display @code{123}. When you execute
                   6224: @code{second-word} it will display @code{-1}.
1.26      crook    6225: 
                   6226: @cindex stack effect of @code{DOES>}-parts
                   6227: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6228: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6229: the stack effect of the defined words, not the stack effect of the
                   6230: following code (the following code expects the address of the body on
                   6231: the top of stack, which is not reflected in the stack comment). This is
                   6232: the convention that I use and recommend (it clashes a bit with using
                   6233: locals declarations for stack effect specification, though).
1.1       anton    6234: 
1.53      anton    6235: @menu
                   6236: * CREATE..DOES> applications::  
                   6237: * CREATE..DOES> details::       
1.63      anton    6238: * Advanced does> usage example::  
1.91      anton    6239: * @code{Const-does>}::          
1.53      anton    6240: @end menu
                   6241: 
                   6242: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6243: @subsubsection Applications of @code{CREATE..DOES>}
                   6244: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6245: 
1.26      crook    6246: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6247: 
1.26      crook    6248: @cindex factoring similar colon definitions
                   6249: When you see a sequence of code occurring several times, and you can
                   6250: identify a meaning, you will factor it out as a colon definition. When
                   6251: you see similar colon definitions, you can factor them using
                   6252: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6253: that look very similar:
1.1       anton    6254: @example
1.26      crook    6255: : ori, ( reg-target reg-source n -- )
                   6256:     0 asm-reg-reg-imm ;
                   6257: : andi, ( reg-target reg-source n -- )
                   6258:     1 asm-reg-reg-imm ;
1.1       anton    6259: @end example
                   6260: 
1.26      crook    6261: @noindent
                   6262: This could be factored with:
                   6263: @example
                   6264: : reg-reg-imm ( op-code -- )
                   6265:     CREATE ,
                   6266: DOES> ( reg-target reg-source n -- )
                   6267:     @@ asm-reg-reg-imm ;
                   6268: 
                   6269: 0 reg-reg-imm ori,
                   6270: 1 reg-reg-imm andi,
                   6271: @end example
1.1       anton    6272: 
1.26      crook    6273: @cindex currying
                   6274: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6275: supply a part of the parameters for a word (known as @dfn{currying} in
                   6276: the functional language community). E.g., @code{+} needs two
                   6277: parameters. Creating versions of @code{+} with one parameter fixed can
                   6278: be done like this:
1.82      anton    6279: 
1.1       anton    6280: @example
1.82      anton    6281: : curry+ ( n1 "name" -- )
1.26      crook    6282:     CREATE ,
                   6283: DOES> ( n2 -- n1+n2 )
                   6284:     @@ + ;
                   6285: 
                   6286:  3 curry+ 3+
                   6287: -2 curry+ 2-
1.1       anton    6288: @end example
                   6289: 
1.91      anton    6290: 
1.63      anton    6291: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6292: @subsubsection The gory details of @code{CREATE..DOES>}
                   6293: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6294: 
1.26      crook    6295: doc-does>
1.1       anton    6296: 
1.26      crook    6297: @cindex @code{DOES>} in a separate definition
                   6298: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6299: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6300: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6301: @example
                   6302: : does1 
                   6303: DOES> ( ... -- ... )
1.44      crook    6304:     ... ;
                   6305: 
                   6306: : does2
                   6307: DOES> ( ... -- ... )
                   6308:     ... ;
                   6309: 
                   6310: : def-word ( ... -- ... )
                   6311:     create ...
                   6312:     IF
                   6313:        does1
                   6314:     ELSE
                   6315:        does2
                   6316:     ENDIF ;
                   6317: @end example
                   6318: 
                   6319: In this example, the selection of whether to use @code{does1} or
1.69      anton    6320: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6321: @code{CREATE}d.
                   6322: 
                   6323: @cindex @code{DOES>} in interpretation state
                   6324: In a standard program you can apply a @code{DOES>}-part only if the last
                   6325: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6326: will override the behaviour of the last word defined in any case. In a
                   6327: standard program, you can use @code{DOES>} only in a colon
                   6328: definition. In Gforth, you can also use it in interpretation state, in a
                   6329: kind of one-shot mode; for example:
                   6330: @example
                   6331: CREATE name ( ... -- ... )
                   6332:   @i{initialization}
                   6333: DOES>
                   6334:   @i{code} ;
                   6335: @end example
                   6336: 
                   6337: @noindent
                   6338: is equivalent to the standard:
                   6339: @example
                   6340: :noname
                   6341: DOES>
                   6342:     @i{code} ;
                   6343: CREATE name EXECUTE ( ... -- ... )
                   6344:     @i{initialization}
                   6345: @end example
                   6346: 
1.53      anton    6347: doc->body
                   6348: 
1.91      anton    6349: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6350: @subsubsection Advanced does> usage example
                   6351: 
                   6352: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6353: for disassembling instructions, that follow a very repetetive scheme:
                   6354: 
                   6355: @example
                   6356: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6357: @var{entry-num} cells @var{table} + !
                   6358: @end example
                   6359: 
                   6360: Of course, this inspires the idea to factor out the commonalities to
                   6361: allow a definition like
                   6362: 
                   6363: @example
                   6364: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6365: @end example
                   6366: 
                   6367: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6368: correlated.  Moreover, before I wrote the disassembler, there already
                   6369: existed code that defines instructions like this:
1.63      anton    6370: 
                   6371: @example
                   6372: @var{entry-num} @var{inst-format} @var{inst-name}
                   6373: @end example
                   6374: 
                   6375: This code comes from the assembler and resides in
                   6376: @file{arch/mips/insts.fs}.
                   6377: 
                   6378: So I had to define the @var{inst-format} words that performed the scheme
                   6379: above when executed.  At first I chose to use run-time code-generation:
                   6380: 
                   6381: @example
                   6382: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6383:   :noname Postpone @var{disasm-operands}
                   6384:   name Postpone sliteral Postpone type Postpone ;
                   6385:   swap cells @var{table} + ! ;
                   6386: @end example
                   6387: 
                   6388: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6389: 
1.63      anton    6390: An alternative would have been to write this using
                   6391: @code{create}/@code{does>}:
                   6392: 
                   6393: @example
                   6394: : @var{inst-format} ( entry-num "name" -- )
                   6395:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6396:   noname create , ( entry-num )
                   6397:   lastxt swap cells @var{table} + !
                   6398: does> ( addr w -- )
                   6399:   \ disassemble instruction w at addr
                   6400:   @@ >r 
                   6401:   @var{disasm-operands}
                   6402:   r> count type ;
                   6403: @end example
                   6404: 
                   6405: Somehow the first solution is simpler, mainly because it's simpler to
                   6406: shift a string from definition-time to use-time with @code{sliteral}
                   6407: than with @code{string,} and friends.
                   6408: 
                   6409: I wrote a lot of words following this scheme and soon thought about
                   6410: factoring out the commonalities among them.  Note that this uses a
                   6411: two-level defining word, i.e., a word that defines ordinary defining
                   6412: words.
                   6413: 
                   6414: This time a solution involving @code{postpone} and friends seemed more
                   6415: difficult (try it as an exercise), so I decided to use a
                   6416: @code{create}/@code{does>} word; since I was already at it, I also used
                   6417: @code{create}/@code{does>} for the lower level (try using
                   6418: @code{postpone} etc. as an exercise), resulting in the following
                   6419: definition:
                   6420: 
                   6421: @example
                   6422: : define-format ( disasm-xt table-xt -- )
                   6423:     \ define an instruction format that uses disasm-xt for
                   6424:     \ disassembling and enters the defined instructions into table
                   6425:     \ table-xt
                   6426:     create 2,
                   6427: does> ( u "inst" -- )
                   6428:     \ defines an anonymous word for disassembling instruction inst,
                   6429:     \ and enters it as u-th entry into table-xt
                   6430:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6431:     noname create 2,      \ define anonymous word
                   6432:     execute lastxt swap ! \ enter xt of defined word into table-xt
                   6433: does> ( addr w -- )
                   6434:     \ disassemble instruction w at addr
                   6435:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6436:     execute ( R: c-addr ) \ disassemble operands
                   6437:     r> count type ; \ print name 
                   6438: @end example
                   6439: 
                   6440: Note that the tables here (in contrast to above) do the @code{cells +}
                   6441: by themselves (that's why you have to pass an xt).  This word is used in
                   6442: the following way:
                   6443: 
                   6444: @example
                   6445: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6446: @end example
                   6447: 
1.71      anton    6448: As shown above, the defined instruction format is then used like this:
                   6449: 
                   6450: @example
                   6451: @var{entry-num} @var{inst-format} @var{inst-name}
                   6452: @end example
                   6453: 
1.63      anton    6454: In terms of currying, this kind of two-level defining word provides the
                   6455: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6456: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6457: the instruction to be disassembled.  
                   6458: 
                   6459: Of course this did not quite fit all the instruction format names used
                   6460: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6461: the parameters into the right form.
                   6462: 
                   6463: If you have trouble following this section, don't worry.  First, this is
                   6464: involved and takes time (and probably some playing around) to
                   6465: understand; second, this is the first two-level
                   6466: @code{create}/@code{does>} word I have written in seventeen years of
                   6467: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6468: have elected to use just a one-level defining word (with some repeating
                   6469: of parameters when using the defining word). So it is not necessary to
                   6470: understand this, but it may improve your understanding of Forth.
1.44      crook    6471: 
                   6472: 
1.91      anton    6473: @node @code{Const-does>},  , Advanced does> usage example, User-defined Defining Words
                   6474: @subsubsection @code{Const-does>}
                   6475: 
                   6476: A frequent use of @code{create}...@code{does>} is for transferring some
                   6477: values from definition-time to run-time.  Gforth supports this use with
                   6478: 
                   6479: doc-const-does>
                   6480: 
                   6481: A typical use of this word is:
                   6482: 
                   6483: @example
                   6484: : curry+ ( n1 "name" -- )
                   6485: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6486:     + ;
                   6487: 
                   6488: 3 curry+ 3+
                   6489: @end example
                   6490: 
                   6491: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6492: definition to run-time.
                   6493: 
                   6494: The advantages of using @code{const-does>} are:
                   6495: 
                   6496: @itemize
                   6497: 
                   6498: @item
                   6499: You don't have to deal with storing and retrieving the values, i.e.,
                   6500: your program becomes more writable and readable.
                   6501: 
                   6502: @item
                   6503: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6504: be optimized away (because you could change the data using
                   6505: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6506: 
                   6507: @end itemize
                   6508: 
                   6509: An ANS Forth implementation of @code{const-does>} is available in
                   6510: @file{compat/const-does.fs}.
                   6511: 
                   6512: 
1.44      crook    6513: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
                   6514: @subsection Deferred words
                   6515: @cindex deferred words
                   6516: 
                   6517: The defining word @code{Defer} allows you to define a word by name
                   6518: without defining its behaviour; the definition of its behaviour is
                   6519: deferred. Here are two situation where this can be useful:
                   6520: 
                   6521: @itemize @bullet
                   6522: @item
                   6523: Where you want to allow the behaviour of a word to be altered later, and
                   6524: for all precompiled references to the word to change when its behaviour
                   6525: is changed.
                   6526: @item
                   6527: For mutual recursion; @xref{Calls and returns}.
                   6528: @end itemize
                   6529: 
                   6530: In the following example, @code{foo} always invokes the version of
                   6531: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6532: always invokes the version that prints ``@code{Hello}''. There is no way
                   6533: of getting @code{foo} to use the later version without re-ordering the
                   6534: source code and recompiling it.
                   6535: 
                   6536: @example
                   6537: : greet ." Good morning" ;
                   6538: : foo ... greet ... ;
                   6539: : greet ." Hello" ;
                   6540: : bar ... greet ... ;
                   6541: @end example
                   6542: 
                   6543: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6544: word. The behaviour of a @code{Defer}red word can be defined and
                   6545: redefined at any time by using @code{IS} to associate the xt of a
                   6546: previously-defined word with it. The previous example becomes:
                   6547: 
                   6548: @example
1.69      anton    6549: Defer greet ( -- )
1.44      crook    6550: : foo ... greet ... ;
                   6551: : bar ... greet ... ;
1.69      anton    6552: : greet1 ( -- ) ." Good morning" ;
                   6553: : greet2 ( -- ) ." Hello" ;
1.44      crook    6554: ' greet2 <IS> greet  \ make greet behave like greet2
                   6555: @end example
                   6556: 
1.69      anton    6557: @progstyle
                   6558: You should write a stack comment for every deferred word, and put only
                   6559: XTs into deferred words that conform to this stack effect.  Otherwise
                   6560: it's too difficult to use the deferred word.
                   6561: 
1.44      crook    6562: A deferred word can be used to improve the statistics-gathering example
                   6563: from @ref{User-defined Defining Words}; rather than edit the
                   6564: application's source code to change every @code{:} to a @code{my:}, do
                   6565: this:
                   6566: 
                   6567: @example
                   6568: : real: : ;     \ retain access to the original
                   6569: defer :         \ redefine as a deferred word
1.69      anton    6570: ' my: <IS> :      \ use special version of :
1.44      crook    6571: \
                   6572: \ load application here
                   6573: \
1.69      anton    6574: ' real: <IS> :    \ go back to the original
1.44      crook    6575: @end example
                   6576: 
                   6577: 
                   6578: One thing to note is that @code{<IS>} consumes its name when it is
                   6579: executed.  If you want to specify the name at compile time, use
                   6580: @code{[IS]}:
                   6581: 
                   6582: @example
                   6583: : set-greet ( xt -- )
                   6584:   [IS] greet ;
                   6585: 
                   6586: ' greet1 set-greet
                   6587: @end example
                   6588: 
1.69      anton    6589: A deferred word can only inherit execution semantics from the xt
                   6590: (because that is all that an xt can represent -- for more discussion of
                   6591: this @pxref{Tokens for Words}); by default it will have default
                   6592: interpretation and compilation semantics deriving from this execution
                   6593: semantics.  However, you can change the interpretation and compilation
                   6594: semantics of the deferred word in the usual ways:
1.44      crook    6595: 
                   6596: @example
                   6597: : bar .... ; compile-only
                   6598: Defer fred immediate
                   6599: Defer jim
                   6600: 
                   6601: ' bar <IS> jim  \ jim has default semantics
                   6602: ' bar <IS> fred \ fred is immediate
                   6603: @end example
                   6604: 
                   6605: doc-defer
                   6606: doc-<is>
                   6607: doc-[is]
                   6608: doc-is
                   6609: @comment TODO document these: what's defers [is]
                   6610: doc-what's
                   6611: doc-defers
                   6612: 
                   6613: @c Use @code{words-deferred} to see a list of deferred words.
                   6614: 
                   6615: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
                   6616: are provided in @file{compat/defer.fs}.
                   6617: 
                   6618: 
1.69      anton    6619: @node Aliases,  , Deferred words, Defining Words
1.44      crook    6620: @subsection Aliases
                   6621: @cindex aliases
1.1       anton    6622: 
1.44      crook    6623: The defining word @code{Alias} allows you to define a word by name that
                   6624: has the same behaviour as some other word. Here are two situation where
                   6625: this can be useful:
1.1       anton    6626: 
1.44      crook    6627: @itemize @bullet
                   6628: @item
                   6629: When you want access to a word's definition from a different word list
                   6630: (for an example of this, see the definition of the @code{Root} word list
                   6631: in the Gforth source).
                   6632: @item
                   6633: When you want to create a synonym; a definition that can be known by
                   6634: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6635: aliases).
                   6636: @end itemize
1.1       anton    6637: 
1.69      anton    6638: Like deferred words, an alias has default compilation and interpretation
                   6639: semantics at the beginning (not the modifications of the other word),
                   6640: but you can change them in the usual ways (@code{immediate},
                   6641: @code{compile-only}). For example:
1.1       anton    6642: 
                   6643: @example
1.44      crook    6644: : foo ... ; immediate
                   6645: 
                   6646: ' foo Alias bar \ bar is not an immediate word
                   6647: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6648: @end example
                   6649: 
1.44      crook    6650: Words that are aliases have the same xt, different headers in the
                   6651: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6652: Words}) and possibly different immediate flags.  An alias can only have
                   6653: default or immediate compilation semantics; you can define aliases for
                   6654: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6655: 
1.44      crook    6656: doc-alias
1.1       anton    6657: 
                   6658: 
1.47      crook    6659: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6660: @section Interpretation and Compilation Semantics
1.26      crook    6661: @cindex semantics, interpretation and compilation
1.1       anton    6662: 
1.71      anton    6663: @c !! state and ' are used without explanation
                   6664: @c example for immediate/compile-only? or is the tutorial enough
                   6665: 
1.26      crook    6666: @cindex interpretation semantics
1.71      anton    6667: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    6668: interpreter does when it encounters the word in interpret state. It also
                   6669: appears in some other contexts, e.g., the execution token returned by
1.71      anton    6670: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   6671: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    6672: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6673: 
1.26      crook    6674: @cindex compilation semantics
1.71      anton    6675: The @dfn{compilation semantics} of a (named) word are what the text
                   6676: interpreter does when it encounters the word in compile state. It also
                   6677: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   6678: compiles@footnote{In standard terminology, ``appends to the current
                   6679: definition''.} the compilation semantics of @i{word}.
1.1       anton    6680: 
1.26      crook    6681: @cindex execution semantics
                   6682: The standard also talks about @dfn{execution semantics}. They are used
                   6683: only for defining the interpretation and compilation semantics of many
                   6684: words. By default, the interpretation semantics of a word are to
                   6685: @code{execute} its execution semantics, and the compilation semantics of
                   6686: a word are to @code{compile,} its execution semantics.@footnote{In
                   6687: standard terminology: The default interpretation semantics are its
                   6688: execution semantics; the default compilation semantics are to append its
                   6689: execution semantics to the execution semantics of the current
                   6690: definition.}
                   6691: 
1.71      anton    6692: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   6693: the text interpreter, ticked, or @code{postpone}d, so they have no
                   6694: interpretation or compilation semantics.  Their behaviour is represented
                   6695: by their XT (@pxref{Tokens for Words}), and we call it execution
                   6696: semantics, too.
                   6697: 
1.26      crook    6698: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6699: 
                   6700: @cindex immediate words
                   6701: @cindex compile-only words
                   6702: You can change the semantics of the most-recently defined word:
                   6703: 
1.44      crook    6704: 
1.26      crook    6705: doc-immediate
                   6706: doc-compile-only
                   6707: doc-restrict
                   6708: 
1.82      anton    6709: By convention, words with non-default compilation semantics (e.g.,
                   6710: immediate words) often have names surrounded with brackets (e.g.,
                   6711: @code{[']}, @pxref{Execution token}).
1.44      crook    6712: 
1.26      crook    6713: Note that ticking (@code{'}) a compile-only word gives an error
                   6714: (``Interpreting a compile-only word'').
1.1       anton    6715: 
1.47      crook    6716: @menu
1.67      anton    6717: * Combined words::              
1.47      crook    6718: @end menu
1.44      crook    6719: 
1.71      anton    6720: 
1.48      anton    6721: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    6722: @subsection Combined Words
                   6723: @cindex combined words
                   6724: 
                   6725: Gforth allows you to define @dfn{combined words} -- words that have an
                   6726: arbitrary combination of interpretation and compilation semantics.
                   6727: 
1.26      crook    6728: doc-interpret/compile:
1.1       anton    6729: 
1.26      crook    6730: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   6731: recommend that you do not define such words, as cute as they may be:
                   6732: they make it hard to get at both parts of the word in some contexts.
                   6733: E.g., assume you want to get an execution token for the compilation
                   6734: part. Instead, define two words, one that embodies the interpretation
                   6735: part, and one that embodies the compilation part.  Once you have done
                   6736: that, you can define a combined word with @code{interpret/compile:} for
                   6737: the convenience of your users.
1.1       anton    6738: 
1.26      crook    6739: You might try to use this feature to provide an optimizing
                   6740: implementation of the default compilation semantics of a word. For
                   6741: example, by defining:
1.1       anton    6742: @example
1.26      crook    6743: :noname
                   6744:    foo bar ;
                   6745: :noname
                   6746:    POSTPONE foo POSTPONE bar ;
1.29      crook    6747: interpret/compile: opti-foobar
1.1       anton    6748: @end example
1.26      crook    6749: 
1.23      crook    6750: @noindent
1.26      crook    6751: as an optimizing version of:
                   6752: 
1.1       anton    6753: @example
1.26      crook    6754: : foobar
                   6755:     foo bar ;
1.1       anton    6756: @end example
                   6757: 
1.26      crook    6758: Unfortunately, this does not work correctly with @code{[compile]},
                   6759: because @code{[compile]} assumes that the compilation semantics of all
                   6760: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    6761: opti-foobar} would compile compilation semantics, whereas
                   6762: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    6763: 
1.26      crook    6764: @cindex state-smart words (are a bad idea)
1.82      anton    6765: @anchor{state-smartness}
1.29      crook    6766: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    6767: by @code{interpret/compile:} (words are state-smart if they check
                   6768: @code{STATE} during execution). E.g., they would try to code
                   6769: @code{foobar} like this:
1.1       anton    6770: 
1.26      crook    6771: @example
                   6772: : foobar
                   6773:   STATE @@
                   6774:   IF ( compilation state )
                   6775:     POSTPONE foo POSTPONE bar
                   6776:   ELSE
                   6777:     foo bar
                   6778:   ENDIF ; immediate
                   6779: @end example
1.1       anton    6780: 
1.26      crook    6781: Although this works if @code{foobar} is only processed by the text
                   6782: interpreter, it does not work in other contexts (like @code{'} or
                   6783: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   6784: for a state-smart word, not for the interpretation semantics of the
                   6785: original @code{foobar}; when you execute this execution token (directly
                   6786: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   6787: state, the result will not be what you expected (i.e., it will not
                   6788: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   6789: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    6790: M. Anton Ertl,
                   6791: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   6792: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    6793: 
1.26      crook    6794: @cindex defining words with arbitrary semantics combinations
                   6795: It is also possible to write defining words that define words with
                   6796: arbitrary combinations of interpretation and compilation semantics. In
                   6797: general, they look like this:
1.1       anton    6798: 
1.26      crook    6799: @example
                   6800: : def-word
                   6801:     create-interpret/compile
1.29      crook    6802:     @i{code1}
1.26      crook    6803: interpretation>
1.29      crook    6804:     @i{code2}
1.26      crook    6805: <interpretation
                   6806: compilation>
1.29      crook    6807:     @i{code3}
1.26      crook    6808: <compilation ;
                   6809: @end example
1.1       anton    6810: 
1.29      crook    6811: For a @i{word} defined with @code{def-word}, the interpretation
                   6812: semantics are to push the address of the body of @i{word} and perform
                   6813: @i{code2}, and the compilation semantics are to push the address of
                   6814: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    6815: can also be defined like this (except that the defined constants don't
                   6816: behave correctly when @code{[compile]}d):
1.1       anton    6817: 
1.26      crook    6818: @example
                   6819: : constant ( n "name" -- )
                   6820:     create-interpret/compile
                   6821:     ,
                   6822: interpretation> ( -- n )
                   6823:     @@
                   6824: <interpretation
                   6825: compilation> ( compilation. -- ; run-time. -- n )
                   6826:     @@ postpone literal
                   6827: <compilation ;
                   6828: @end example
1.1       anton    6829: 
1.44      crook    6830: 
1.26      crook    6831: doc-create-interpret/compile
                   6832: doc-interpretation>
                   6833: doc-<interpretation
                   6834: doc-compilation>
                   6835: doc-<compilation
1.1       anton    6836: 
1.44      crook    6837: 
1.29      crook    6838: Words defined with @code{interpret/compile:} and
1.26      crook    6839: @code{create-interpret/compile} have an extended header structure that
                   6840: differs from other words; however, unless you try to access them with
                   6841: plain address arithmetic, you should not notice this. Words for
                   6842: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    6843: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   6844: with @code{create-interpret/compile}.
1.1       anton    6845: 
1.44      crook    6846: 
1.47      crook    6847: @c -------------------------------------------------------------
1.81      anton    6848: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    6849: @section Tokens for Words
                   6850: @cindex tokens for words
                   6851: 
                   6852: This section describes the creation and use of tokens that represent
                   6853: words.
                   6854: 
1.71      anton    6855: @menu
                   6856: * Execution token::             represents execution/interpretation semantics
                   6857: * Compilation token::           represents compilation semantics
                   6858: * Name token::                  represents named words
                   6859: @end menu
1.47      crook    6860: 
1.71      anton    6861: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   6862: @subsection Execution token
1.47      crook    6863: 
                   6864: @cindex xt
                   6865: @cindex execution token
1.71      anton    6866: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   6867: You can use @code{execute} to invoke this behaviour.
1.47      crook    6868: 
1.71      anton    6869: @cindex tick (')
                   6870: You can use @code{'} to get an execution token that represents the
                   6871: interpretation semantics of a named word:
1.47      crook    6872: 
                   6873: @example
1.97      anton    6874: 5 ' .   ( n xt ) 
                   6875: execute ( )      \ execute the xt (i.e., ".")
1.71      anton    6876: @end example
1.47      crook    6877: 
1.71      anton    6878: doc-'
                   6879: 
                   6880: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   6881: when it is compiled, and compiles the resulting XT:
                   6882: 
                   6883: @example
                   6884: : foo ['] . execute ;
                   6885: 5 foo
                   6886: : bar ' execute ; \ by contrast,
                   6887: 5 bar .           \ ' parses "." when bar executes
                   6888: @end example
                   6889: 
                   6890: doc-[']
                   6891: 
                   6892: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   6893: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   6894: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   6895: compile-only words (because these words have no interpretation
                   6896: semantics).  You might get what you want by using @code{COMP' @i{word}
                   6897: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   6898: token}).
                   6899: 
                   6900: Another way to get an XT is @code{:noname} or @code{lastxt}
                   6901: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   6902: for the only behaviour the word has (the execution semantics).  For
                   6903: named words, @code{lastxt} produces an XT for the same behaviour it
                   6904: would produce if the word was defined anonymously.
                   6905: 
                   6906: @example
                   6907: :noname ." hello" ;
                   6908: execute
1.47      crook    6909: @end example
                   6910: 
1.71      anton    6911: An XT occupies one cell and can be manipulated like any other cell.
                   6912: 
1.47      crook    6913: @cindex code field address
                   6914: @cindex CFA
1.71      anton    6915: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   6916: operations that produce or consume it).  For old hands: In Gforth, the
                   6917: XT is implemented as a code field address (CFA).
                   6918: 
                   6919: doc-execute
                   6920: doc-perform
                   6921: 
                   6922: @node Compilation token, Name token, Execution token, Tokens for Words
                   6923: @subsection Compilation token
1.47      crook    6924: 
                   6925: @cindex compilation token
1.71      anton    6926: @cindex CT (compilation token)
                   6927: Gforth represents the compilation semantics of a named word by a
1.47      crook    6928: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   6929: @i{xt} is an execution token. The compilation semantics represented by
                   6930: the compilation token can be performed with @code{execute}, which
                   6931: consumes the whole compilation token, with an additional stack effect
                   6932: determined by the represented compilation semantics.
                   6933: 
                   6934: At present, the @i{w} part of a compilation token is an execution token,
                   6935: and the @i{xt} part represents either @code{execute} or
                   6936: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   6937: word. If the word has default compilation semantics, the @i{xt} will
                   6938: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   6939: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   6940: knowledge, unless necessary; future versions of Gforth may introduce
                   6941: unusual compilation tokens (e.g., a compilation token that represents
                   6942: the compilation semantics of a literal).
                   6943: 
1.71      anton    6944: You can perform the compilation semantics represented by the compilation
                   6945: token with @code{execute}.  You can compile the compilation semantics
                   6946: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   6947: equivalent to @code{postpone @i{word}}.
                   6948: 
                   6949: doc-[comp']
                   6950: doc-comp'
                   6951: doc-postpone,
                   6952: 
                   6953: @node Name token,  , Compilation token, Tokens for Words
                   6954: @subsection Name token
1.47      crook    6955: 
                   6956: @cindex name token
                   6957: @cindex name field address
                   6958: @cindex NFA
1.71      anton    6959: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47      crook    6960: Gforth, the abstract data type @emph{name token} is implemented as a
                   6961: name field address (NFA).
                   6962: 
                   6963: doc-find-name
                   6964: doc-name>int
                   6965: doc-name?int
                   6966: doc-name>comp
                   6967: doc-name>string
1.109     anton    6968: doc-id.
                   6969: doc-.name
                   6970: doc-.id
1.47      crook    6971: 
1.81      anton    6972: @c ----------------------------------------------------------
                   6973: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   6974: @section Compiling words
                   6975: @cindex compiling words
                   6976: @cindex macros
                   6977: 
                   6978: In contrast to most other languages, Forth has no strict boundary
1.82      anton    6979: between compilation and run-time.  E.g., you can run arbitrary code
                   6980: between defining words (or for computing data used by defining words
                   6981: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   6982: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   6983: running arbitrary code while compiling a colon definition (exception:
                   6984: you must not allot dictionary space).
                   6985: 
                   6986: @menu
                   6987: * Literals::                    Compiling data values
                   6988: * Macros::                      Compiling words
                   6989: @end menu
                   6990: 
                   6991: @node Literals, Macros, Compiling words, Compiling words
                   6992: @subsection Literals
                   6993: @cindex Literals
                   6994: 
                   6995: The simplest and most frequent example is to compute a literal during
                   6996: compilation.  E.g., the following definition prints an array of strings,
                   6997: one string per line:
                   6998: 
                   6999: @example
                   7000: : .strings ( addr u -- ) \ gforth
                   7001:     2* cells bounds U+DO
                   7002:        cr i 2@@ type
                   7003:     2 cells +LOOP ;  
                   7004: @end example
1.81      anton    7005: 
1.82      anton    7006: With a simple-minded compiler like Gforth's, this computes @code{2
                   7007: cells} on every loop iteration.  You can compute this value once and for
                   7008: all at compile time and compile it into the definition like this:
                   7009: 
                   7010: @example
                   7011: : .strings ( addr u -- ) \ gforth
                   7012:     2* cells bounds U+DO
                   7013:        cr i 2@@ type
                   7014:     [ 2 cells ] literal +LOOP ;  
                   7015: @end example
                   7016: 
                   7017: @code{[} switches the text interpreter to interpret state (you will get
                   7018: an @code{ok} prompt if you type this example interactively and insert a
                   7019: newline between @code{[} and @code{]}), so it performs the
                   7020: interpretation semantics of @code{2 cells}; this computes a number.
                   7021: @code{]} switches the text interpreter back into compile state.  It then
                   7022: performs @code{Literal}'s compilation semantics, which are to compile
                   7023: this number into the current word.  You can decompile the word with
                   7024: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7025: 
1.82      anton    7026: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7027: *} in this way.
1.81      anton    7028: 
1.82      anton    7029: doc-[
                   7030: doc-]
1.81      anton    7031: doc-literal
                   7032: doc-]L
1.82      anton    7033: 
                   7034: There are also words for compiling other data types than single cells as
                   7035: literals:
                   7036: 
1.81      anton    7037: doc-2literal
                   7038: doc-fliteral
1.82      anton    7039: doc-sliteral
                   7040: 
                   7041: @cindex colon-sys, passing data across @code{:}
                   7042: @cindex @code{:}, passing data across
                   7043: You might be tempted to pass data from outside a colon definition to the
                   7044: inside on the data stack.  This does not work, because @code{:} puhes a
                   7045: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7046: 
                   7047: @example
                   7048: 5 : foo literal ; \ error: "unstructured"
                   7049: @end example
                   7050: 
                   7051: Instead, you have to pass the value in some other way, e.g., through a
                   7052: variable:
                   7053: 
                   7054: @example
                   7055: variable temp
                   7056: 5 temp !
                   7057: : foo [ temp @@ ] literal ;
                   7058: @end example
                   7059: 
                   7060: 
                   7061: @node Macros,  , Literals, Compiling words
                   7062: @subsection Macros
                   7063: @cindex Macros
                   7064: @cindex compiling compilation semantics
                   7065: 
                   7066: @code{Literal} and friends compile data values into the current
                   7067: definition.  You can also write words that compile other words into the
                   7068: current definition.  E.g.,
                   7069: 
                   7070: @example
                   7071: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7072:   POSTPONE + ;
                   7073: 
                   7074: : foo ( n1 n2 -- n )
                   7075:   [ compile-+ ] ;
                   7076: 1 2 foo .
                   7077: @end example
                   7078: 
                   7079: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7080: What happens in this example?  @code{Postpone} compiles the compilation
                   7081: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7082: executes @code{compile-+} and thus the compilation semantics of +, which
                   7083: compile (the execution semantics of) @code{+} into
                   7084: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7085: should only be executed in compile state, so this example is not
                   7086: guaranteed to work on all standard systems, but on any decent system it
                   7087: will work.}
                   7088: 
                   7089: doc-postpone
                   7090: doc-[compile]
                   7091: 
                   7092: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7093: so you do not have to switch to interpret state to execute them;
                   7094: mopifying the last example accordingly produces:
                   7095: 
                   7096: @example
                   7097: : [compile-+] ( compilation: --; interpretation: -- )
                   7098:   \ compiled code: ( n1 n2 -- n )
                   7099:   POSTPONE + ; immediate
                   7100: 
                   7101: : foo ( n1 n2 -- n )
                   7102:   [compile-+] ;
                   7103: 1 2 foo .
                   7104: @end example
                   7105: 
                   7106: Immediate compiling words are similar to macros in other languages (in
                   7107: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7108: 
                   7109: @itemize @bullet
                   7110: 
                   7111: @item
                   7112: You use the same language for defining and processing macros, not a
                   7113: separate preprocessing language and processor.
                   7114: 
                   7115: @item
                   7116: Consequently, the full power of Forth is available in macro definitions.
                   7117: E.g., you can perform arbitrarily complex computations, or generate
                   7118: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7119: Tutorial}).  This power is very useful when writing a parser generators
                   7120: or other code-generating software.
                   7121: 
                   7122: @item
                   7123: Macros defined using @code{postpone} etc. deal with the language at a
                   7124: higher level than strings; name binding happens at macro definition
                   7125: time, so you can avoid the pitfalls of name collisions that can happen
                   7126: in C macros.  Of course, Forth is a liberal language and also allows to
                   7127: shoot yourself in the foot with text-interpreted macros like
                   7128: 
                   7129: @example
                   7130: : [compile-+] s" +" evaluate ; immediate
                   7131: @end example
                   7132: 
                   7133: Apart from binding the name at macro use time, using @code{evaluate}
                   7134: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7135: @end itemize
                   7136: 
                   7137: You may want the macro to compile a number into a word.  The word to do
                   7138: it is @code{literal}, but you have to @code{postpone} it, so its
                   7139: compilation semantics take effect when the macro is executed, not when
                   7140: it is compiled:
                   7141: 
                   7142: @example
                   7143: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7144:   5 POSTPONE literal ; immediate
                   7145: 
                   7146: : foo [compile-5] ;
                   7147: foo .
                   7148: @end example
                   7149: 
                   7150: You may want to pass parameters to a macro, that the macro should
                   7151: compile into the current definition.  If the parameter is a number, then
                   7152: you can use @code{postpone literal} (similar for other values).
                   7153: 
                   7154: If you want to pass a word that is to be compiled, the usual way is to
                   7155: pass an execution token and @code{compile,} it:
                   7156: 
                   7157: @example
                   7158: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7159:   dup compile, compile, ;
                   7160: 
                   7161: : 2+ ( n1 -- n2 )
                   7162:   [ ' 1+ twice1 ] ;
                   7163: @end example
                   7164: 
                   7165: doc-compile,
                   7166: 
                   7167: An alternative available in Gforth, that allows you to pass compile-only
                   7168: words as parameters is to use the compilation token (@pxref{Compilation
                   7169: token}).  The same example in this technique:
                   7170: 
                   7171: @example
                   7172: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7173:   2dup 2>r execute 2r> execute ;
                   7174: 
                   7175: : 2+ ( n1 -- n2 )
                   7176:   [ comp' 1+ twice ] ;
                   7177: @end example
                   7178: 
                   7179: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7180: works even if the executed compilation semantics has an effect on the
                   7181: data stack.
                   7182: 
                   7183: You can also define complete definitions with these words; this provides
                   7184: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7185: Words}).  E.g., instead of
                   7186: 
                   7187: @example
                   7188: : curry+ ( n1 "name" -- )
                   7189:     CREATE ,
                   7190: DOES> ( n2 -- n1+n2 )
                   7191:     @@ + ;
                   7192: @end example
                   7193: 
                   7194: you could define
                   7195: 
                   7196: @example
                   7197: : curry+ ( n1 "name" -- )
                   7198:   \ name execution: ( n2 -- n1+n2 )
                   7199:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7200: 
1.82      anton    7201: -3 curry+ 3-
                   7202: see 3-
                   7203: @end example
1.81      anton    7204: 
1.82      anton    7205: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7206: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7207: 
1.82      anton    7208: This way of writing defining words is sometimes more, sometimes less
                   7209: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7210: example}).  One advantage of this method is that it can be optimized
                   7211: better, because the compiler knows that the value compiled with
                   7212: @code{literal} is fixed, whereas the data associated with a
                   7213: @code{create}d word can be changed.
1.47      crook    7214: 
1.26      crook    7215: @c ----------------------------------------------------------
1.111     anton    7216: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26      crook    7217: @section  The Text Interpreter
                   7218: @cindex interpreter - outer
                   7219: @cindex text interpreter
                   7220: @cindex outer interpreter
1.1       anton    7221: 
1.34      anton    7222: @c Should we really describe all these ugly details?  IMO the text
                   7223: @c interpreter should be much cleaner, but that may not be possible within
                   7224: @c ANS Forth. - anton
1.44      crook    7225: @c nac-> I wanted to explain how it works to show how you can exploit
                   7226: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7227: @c some of these gory details was very helpful to me. None of the textbooks
                   7228: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7229: @c seems to positively avoid going into too much detail for some of
                   7230: @c the internals.
1.34      anton    7231: 
1.71      anton    7232: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7233: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7234: @c whether we should have a chapter before "Words" that describes some
                   7235: @c basic concepts referred to in words, and a chapter after "Words" that
                   7236: @c describes implementation details.
                   7237: 
1.29      crook    7238: The text interpreter@footnote{This is an expanded version of the
                   7239: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7240: that processes input from the current input device. It is also called
                   7241: the outer interpreter, in contrast to the inner interpreter
                   7242: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7243: implementations.
1.27      crook    7244: 
1.29      crook    7245: @cindex interpret state
                   7246: @cindex compile state
                   7247: The text interpreter operates in one of two states: @dfn{interpret
                   7248: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7249: aptly-named variable @code{state}.
1.29      crook    7250: 
                   7251: This section starts by describing how the text interpreter behaves when
                   7252: it is in interpret state, processing input from the user input device --
                   7253: the keyboard. This is the mode that a Forth system is in after it starts
                   7254: up.
                   7255: 
                   7256: @cindex input buffer
                   7257: @cindex terminal input buffer
                   7258: The text interpreter works from an area of memory called the @dfn{input
                   7259: buffer}@footnote{When the text interpreter is processing input from the
                   7260: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7261: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7262: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7263: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7264: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7265: sequence of non-space characters) until it reaches either a space
                   7266: character or the end of the buffer. Having parsed a string, it makes two
                   7267: attempts to process it:
1.27      crook    7268: 
1.29      crook    7269: @cindex dictionary
1.27      crook    7270: @itemize @bullet
                   7271: @item
1.29      crook    7272: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7273: string is found, the string names a @dfn{definition} (also known as a
                   7274: @dfn{word}) and the dictionary search returns information that allows
                   7275: the text interpreter to perform the word's @dfn{interpretation
                   7276: semantics}. In most cases, this simply means that the word will be
                   7277: executed.
1.27      crook    7278: @item
                   7279: If the string is not found in the dictionary, the text interpreter
1.29      crook    7280: attempts to treat it as a number, using the rules described in
                   7281: @ref{Number Conversion}. If the string represents a legal number in the
                   7282: current radix, the number is pushed onto a parameter stack (the data
                   7283: stack for integers, the floating-point stack for floating-point
                   7284: numbers).
                   7285: @end itemize
                   7286: 
                   7287: If both attempts fail, or if the word is found in the dictionary but has
                   7288: no interpretation semantics@footnote{This happens if the word was
                   7289: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7290: remainder of the input buffer, issues an error message and waits for
                   7291: more input. If one of the attempts succeeds, the text interpreter
                   7292: repeats the parsing process until the whole of the input buffer has been
                   7293: processed, at which point it prints the status message ``@code{ ok}''
                   7294: and waits for more input.
                   7295: 
1.71      anton    7296: @c anton: this should be in the input stream subsection (or below it)
                   7297: 
1.29      crook    7298: @cindex parse area
                   7299: The text interpreter keeps track of its position in the input buffer by
                   7300: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7301: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7302: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7303: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7304: the text interpreter processes the contents of the input buffer by
                   7305: parsing strings from the parse area until the parse area is empty.}.
                   7306: This example shows how @code{>IN} changes as the text interpreter parses
                   7307: the input buffer:
                   7308: 
                   7309: @example
                   7310: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7311:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7312: 
                   7313: 1 2 3 remaining + remaining . 
                   7314: 
                   7315: : foo 1 2 3 remaining SWAP remaining ;
                   7316: @end example
                   7317: 
                   7318: @noindent
                   7319: The result is:
                   7320: 
                   7321: @example
                   7322: ->+ remaining .<-
                   7323: ->.<-5  ok
                   7324: 
                   7325: ->SWAP remaining ;-<
                   7326: ->;<-  ok
                   7327: @end example
                   7328: 
                   7329: @cindex parsing words
                   7330: The value of @code{>IN} can also be modified by a word in the input
                   7331: buffer that is executed by the text interpreter.  This means that a word
                   7332: can ``trick'' the text interpreter into either skipping a section of the
                   7333: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7334: section twice. For example:
1.27      crook    7335: 
1.29      crook    7336: @example
1.71      anton    7337: : lat ." <<foo>>" ;
                   7338: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7339: @end example
                   7340: 
                   7341: @noindent
                   7342: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7343: for the reader: what would happen if the @code{3} were replaced with
                   7344: @code{4}?}:
                   7345: 
                   7346: @example
1.71      anton    7347: <<bar>><<foo>>
1.29      crook    7348: @end example
                   7349: 
1.71      anton    7350: This technique can be used to work around some of the interoperability
                   7351: problems of parsing words.  Of course, it's better to avoid parsing
                   7352: words where possible.
                   7353: 
1.29      crook    7354: @noindent
                   7355: Two important notes about the behaviour of the text interpreter:
1.27      crook    7356: 
                   7357: @itemize @bullet
                   7358: @item
                   7359: It processes each input string to completion before parsing additional
1.29      crook    7360: characters from the input buffer.
                   7361: @item
                   7362: It treats the input buffer as a read-only region (and so must your code).
                   7363: @end itemize
                   7364: 
                   7365: @noindent
                   7366: When the text interpreter is in compile state, its behaviour changes in
                   7367: these ways:
                   7368: 
                   7369: @itemize @bullet
                   7370: @item
                   7371: If a parsed string is found in the dictionary, the text interpreter will
                   7372: perform the word's @dfn{compilation semantics}. In most cases, this
                   7373: simply means that the execution semantics of the word will be appended
                   7374: to the current definition.
1.27      crook    7375: @item
1.29      crook    7376: When a number is encountered, it is compiled into the current definition
                   7377: (as a literal) rather than being pushed onto a parameter stack.
                   7378: @item
                   7379: If an error occurs, @code{state} is modified to put the text interpreter
                   7380: back into interpret state.
                   7381: @item
                   7382: Each time a line is entered from the keyboard, Gforth prints
                   7383: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7384: @end itemize
                   7385: 
                   7386: @cindex text interpreter - input sources
                   7387: When the text interpreter is using an input device other than the
                   7388: keyboard, its behaviour changes in these ways:
                   7389: 
                   7390: @itemize @bullet
                   7391: @item
                   7392: When the parse area is empty, the text interpreter attempts to refill
                   7393: the input buffer from the input source. When the input source is
1.71      anton    7394: exhausted, the input source is set back to the previous input source.
1.29      crook    7395: @item
                   7396: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7397: time the parse area is emptied.
                   7398: @item
                   7399: If an error occurs, the input source is set back to the user input
                   7400: device.
1.27      crook    7401: @end itemize
1.21      crook    7402: 
1.49      anton    7403: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7404: 
1.26      crook    7405: doc->in
1.27      crook    7406: doc-source
                   7407: 
1.26      crook    7408: doc-tib
                   7409: doc-#tib
1.1       anton    7410: 
1.44      crook    7411: 
1.26      crook    7412: @menu
1.67      anton    7413: * Input Sources::               
                   7414: * Number Conversion::           
                   7415: * Interpret/Compile states::    
                   7416: * Interpreter Directives::      
1.26      crook    7417: @end menu
1.1       anton    7418: 
1.29      crook    7419: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7420: @subsection Input Sources
                   7421: @cindex input sources
                   7422: @cindex text interpreter - input sources
                   7423: 
1.44      crook    7424: By default, the text interpreter processes input from the user input
1.29      crook    7425: device (the keyboard) when Forth starts up. The text interpreter can
                   7426: process input from any of these sources:
                   7427: 
                   7428: @itemize @bullet
                   7429: @item
                   7430: The user input device -- the keyboard.
                   7431: @item
                   7432: A file, using the words described in @ref{Forth source files}.
                   7433: @item
                   7434: A block, using the words described in @ref{Blocks}.
                   7435: @item
                   7436: A text string, using @code{evaluate}.
                   7437: @end itemize
                   7438: 
                   7439: A program can identify the current input device from the values of
                   7440: @code{source-id} and @code{blk}.
                   7441: 
1.44      crook    7442: 
1.29      crook    7443: doc-source-id
                   7444: doc-blk
                   7445: 
                   7446: doc-save-input
                   7447: doc-restore-input
                   7448: 
                   7449: doc-evaluate
1.111     anton    7450: doc-query
1.1       anton    7451: 
1.29      crook    7452: 
1.44      crook    7453: 
1.29      crook    7454: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7455: @subsection Number Conversion
                   7456: @cindex number conversion
                   7457: @cindex double-cell numbers, input format
                   7458: @cindex input format for double-cell numbers
                   7459: @cindex single-cell numbers, input format
                   7460: @cindex input format for single-cell numbers
                   7461: @cindex floating-point numbers, input format
                   7462: @cindex input format for floating-point numbers
1.1       anton    7463: 
1.29      crook    7464: This section describes the rules that the text interpreter uses when it
                   7465: tries to convert a string into a number.
1.1       anton    7466: 
1.26      crook    7467: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7468: number base@footnote{For example, 0-9 when the number base is decimal or
                   7469: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7470: 
1.26      crook    7471: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7472: 
1.29      crook    7473: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7474: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7475: 
1.26      crook    7476: Let * represent any number of instances of the previous character
                   7477: (including none).
1.1       anton    7478: 
1.26      crook    7479: Let any other character represent itself.
1.1       anton    7480: 
1.29      crook    7481: @noindent
1.26      crook    7482: Now, the conversion rules are:
1.21      crook    7483: 
1.26      crook    7484: @itemize @bullet
                   7485: @item
                   7486: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7487: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7488: @item
                   7489: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7490: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7491: arithmetic. Examples are -45 -5681 -0
                   7492: @item
                   7493: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7494: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7495: (all three of these represent the same number).
1.26      crook    7496: @item
                   7497: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7498: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7499: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7500: -34.65 (all three of these represent the same number).
1.26      crook    7501: @item
1.29      crook    7502: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7503: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7504: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7505: number) +12.E-4
1.26      crook    7506: @end itemize
1.1       anton    7507: 
1.26      crook    7508: By default, the number base used for integer number conversion is given
1.35      anton    7509: by the contents of the variable @code{base}.  Note that a lot of
                   7510: confusion can result from unexpected values of @code{base}.  If you
                   7511: change @code{base} anywhere, make sure to save the old value and restore
                   7512: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   7513: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7514: 
1.29      crook    7515: doc-dpl
1.26      crook    7516: doc-base
                   7517: doc-hex
                   7518: doc-decimal
1.1       anton    7519: 
1.44      crook    7520: 
1.26      crook    7521: @cindex '-prefix for character strings
                   7522: @cindex &-prefix for decimal numbers
                   7523: @cindex %-prefix for binary numbers
                   7524: @cindex $-prefix for hexadecimal numbers
1.35      anton    7525: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7526: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7527: implementing @code{$} etc. as parsing words that process the subsequent
                   7528: number in the input stream and push it onto the stack. For example, see
                   7529: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7530: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7531: is required between the prefix and the number.} before the first digit
                   7532: of an (integer) number. Four prefixes are supported:
1.1       anton    7533: 
1.26      crook    7534: @itemize @bullet
                   7535: @item
1.35      anton    7536: @code{&} -- decimal
1.26      crook    7537: @item
1.35      anton    7538: @code{%} -- binary
1.26      crook    7539: @item
1.35      anton    7540: @code{$} -- hexadecimal
1.26      crook    7541: @item
1.35      anton    7542: @code{'} -- base @code{max-char+1}
1.26      crook    7543: @end itemize
1.1       anton    7544: 
1.26      crook    7545: Here are some examples, with the equivalent decimal number shown after
                   7546: in braces:
1.1       anton    7547: 
1.26      crook    7548: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   7549: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   7550: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   7551: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7552: 
1.26      crook    7553: @cindex number conversion - traps for the unwary
1.29      crook    7554: @noindent
1.26      crook    7555: Number conversion has a number of traps for the unwary:
1.1       anton    7556: 
1.26      crook    7557: @itemize @bullet
                   7558: @item
                   7559: You cannot determine the current number base using the code sequence
1.35      anton    7560: @code{base @@ .} -- the number base is always 10 in the current number
                   7561: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7562: @item
                   7563: If the number base is set to a value greater than 14 (for example,
                   7564: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7565: it to be intepreted as either a single-precision integer or a
                   7566: floating-point number (Gforth treats it as an integer). The ambiguity
                   7567: can be resolved by explicitly stating the sign of the mantissa and/or
                   7568: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7569: ambiguity arises; either representation will be treated as a
                   7570: floating-point number.
                   7571: @item
1.29      crook    7572: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7573: It is used to specify file types.
                   7574: @item
1.72      anton    7575: ANS Forth requires the @code{.} of a double-precision number to be the
                   7576: final character in the string.  Gforth allows the @code{.} to be
                   7577: anywhere after the first digit.
1.26      crook    7578: @item
                   7579: The number conversion process does not check for overflow.
                   7580: @item
1.72      anton    7581: In an ANS Forth program @code{base} is required to be decimal when
                   7582: converting floating-point numbers.  In Gforth, number conversion to
                   7583: floating-point numbers always uses base &10, irrespective of the value
                   7584: of @code{base}.
1.26      crook    7585: @end itemize
1.1       anton    7586: 
1.49      anton    7587: You can read numbers into your programs with the words described in
                   7588: @ref{Input}.
1.1       anton    7589: 
1.82      anton    7590: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    7591: @subsection Interpret/Compile states
                   7592: @cindex Interpret/Compile states
1.1       anton    7593: 
1.29      crook    7594: A standard program is not permitted to change @code{state}
                   7595: explicitly. However, it can change @code{state} implicitly, using the
                   7596: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7597: @code{state} to interpret state, and therefore the text interpreter
                   7598: starts interpreting. When @code{]} is executed it switches @code{state}
                   7599: to compile state and therefore the text interpreter starts
1.44      crook    7600: compiling. The most common usage for these words is for switching into
                   7601: interpret state and back from within a colon definition; this technique
1.49      anton    7602: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7603: for conditional compilation (for an example, @pxref{Interpreter
                   7604: Directives}).
1.44      crook    7605: 
1.35      anton    7606: 
                   7607: @c This is a bad example: It's non-standard, and it's not necessary.
                   7608: @c However, I can't think of a good example for switching into compile
                   7609: @c state when there is no current word (@code{state}-smart words are not a
                   7610: @c good reason).  So maybe we should use an example for switching into
                   7611: @c interpret @code{state} in a colon def. - anton
1.44      crook    7612: @c nac-> I agree. I started out by putting in the example, then realised
                   7613: @c that it was non-ANS, so wrote more words around it. I hope this
                   7614: @c re-written version is acceptable to you. I do want to keep the example
                   7615: @c as it is helpful for showing what is and what is not portable, particularly
                   7616: @c where it outlaws a style in common use.
                   7617: 
1.72      anton    7618: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    7619: @c that, we can also show what's not.  In any case, I have written a
                   7620: @c section Compiling Words which also deals with [ ].
1.35      anton    7621: 
1.95      anton    7622: @c  !! The following example does not work in Gforth 0.5.9 or later.
1.29      crook    7623: 
1.95      anton    7624: @c  @code{[} and @code{]} also give you the ability to switch into compile
                   7625: @c  state and back, but we cannot think of any useful Standard application
                   7626: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
                   7627: 
                   7628: @c  @example
                   7629: @c  : AA ." this is A" ;
                   7630: @c  : BB ." this is B" ;
                   7631: @c  : CC ." this is C" ;
                   7632: 
                   7633: @c  create table ] aa bb cc [
                   7634: 
                   7635: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7636: @c    cells table + @@ execute ;
                   7637: @c  @end example
                   7638: 
                   7639: @c  This example builds a jump table; @code{0 go} will display ``@code{this
                   7640: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7641: @c  defining @code{table} like this:
                   7642: 
                   7643: @c  @example
                   7644: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   7645: @c  @end example
                   7646: 
                   7647: @c  The problem with this code is that the definition of @code{table} is not
                   7648: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7649: @c  @i{may} work on systems where code space and data space co-incide, the
                   7650: @c  Standard only allows data space to be assigned for a @code{CREATE}d
                   7651: @c  word. In addition, the Standard only allows @code{@@} to access data
                   7652: @c  space, whilst this example is using it to access code space. The only
                   7653: @c  portable, Standard way to build this table is to build it in data space,
                   7654: @c  like this:
                   7655: 
                   7656: @c  @example
                   7657: @c  create table ' aa , ' bb , ' cc ,
                   7658: @c  @end example
1.29      crook    7659: 
1.95      anton    7660: @c  doc-state
1.44      crook    7661: 
1.29      crook    7662: 
1.82      anton    7663: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    7664: @subsection Interpreter Directives
                   7665: @cindex interpreter directives
1.72      anton    7666: @cindex conditional compilation
1.1       anton    7667: 
1.29      crook    7668: These words are usually used in interpret state; typically to control
                   7669: which parts of a source file are processed by the text
1.26      crook    7670: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7671: supplements these with a rich set of immediate control structure words
                   7672: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7673: used in compile state (@pxref{Control Structures}). Typical usages:
                   7674: 
                   7675: @example
1.72      anton    7676: FALSE Constant HAVE-ASSEMBLER
1.29      crook    7677: .
                   7678: .
1.72      anton    7679: HAVE-ASSEMBLER [IF]
1.29      crook    7680: : ASSEMBLER-FEATURE
                   7681:   ...
                   7682: ;
                   7683: [ENDIF]
                   7684: .
                   7685: .
                   7686: : SEE
                   7687:   ... \ general-purpose SEE code
1.72      anton    7688:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    7689:   ... \ assembler-specific SEE code
                   7690:   [ [ENDIF] ]
                   7691: ;
                   7692: @end example
1.1       anton    7693: 
1.44      crook    7694: 
1.26      crook    7695: doc-[IF]
                   7696: doc-[ELSE]
                   7697: doc-[THEN]
                   7698: doc-[ENDIF]
1.1       anton    7699: 
1.26      crook    7700: doc-[IFDEF]
                   7701: doc-[IFUNDEF]
1.1       anton    7702: 
1.26      crook    7703: doc-[?DO]
                   7704: doc-[DO]
                   7705: doc-[FOR]
                   7706: doc-[LOOP]
                   7707: doc-[+LOOP]
                   7708: doc-[NEXT]
1.1       anton    7709: 
1.26      crook    7710: doc-[BEGIN]
                   7711: doc-[UNTIL]
                   7712: doc-[AGAIN]
                   7713: doc-[WHILE]
                   7714: doc-[REPEAT]
1.1       anton    7715: 
1.27      crook    7716: 
1.26      crook    7717: @c -------------------------------------------------------------
1.111     anton    7718: @node The Input Stream, Word Lists, The Text Interpreter, Words
                   7719: @section The Input Stream
                   7720: @cindex input stream
                   7721: 
                   7722: @c !! integrate this better with the "Text Interpreter" section
                   7723: The text interpreter reads from the input stream, which can come from
                   7724: several sources (@pxref{Input Sources}).  Some words, in particular
                   7725: defining words, but also words like @code{'}, read parameters from the
                   7726: input stream instead of from the stack.
                   7727: 
                   7728: Such words are called parsing words, because they parse the input
                   7729: stream.  Parsing words are hard to use in other words, because it is
                   7730: hard to pass program-generated parameters through the input stream.
                   7731: They also usually have an unintuitive combination of interpretation and
                   7732: compilation semantics when implemented naively, leading to various
                   7733: approaches that try to produce a more intuitive behaviour
                   7734: (@pxref{Combined words}).
                   7735: 
                   7736: It should be obvious by now that parsing words are a bad idea.  If you
                   7737: want to implement a parsing word for convenience, also provide a factor
                   7738: of the word that does not parse, but takes the parameters on the stack.
                   7739: To implement the parsing word on top if it, you can use the following
                   7740: words:
                   7741: 
                   7742: @c anton: these belong in the input stream section
                   7743: doc-parse
                   7744: doc-parse-word
                   7745: doc-name
                   7746: doc-word
                   7747: doc-\"-parse
                   7748: doc-refill
                   7749: 
                   7750: Conversely, if you have the bad luck (or lack of foresight) to have to
                   7751: deal with parsing words without having such factors, how do you pass a
                   7752: string that is not in the input stream to it?
                   7753: 
                   7754: doc-execute-parsing
                   7755: 
                   7756: If you want to run a parsing word on a file, the following word should
                   7757: help:
                   7758: 
                   7759: doc-execute-parsing-file
                   7760: 
                   7761: @c -------------------------------------------------------------
                   7762: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26      crook    7763: @section Word Lists
                   7764: @cindex word lists
1.32      anton    7765: @cindex header space
1.1       anton    7766: 
1.36      anton    7767: A wordlist is a list of named words; you can add new words and look up
                   7768: words by name (and you can remove words in a restricted way with
                   7769: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   7770: 
                   7771: @cindex search order stack
                   7772: The text interpreter searches the wordlists present in the search order
                   7773: (a stack of wordlists), from the top to the bottom.  Within each
                   7774: wordlist, the search starts conceptually at the newest word; i.e., if
                   7775: two words in a wordlist have the same name, the newer word is found.
1.1       anton    7776: 
1.26      crook    7777: @cindex compilation word list
1.36      anton    7778: New words are added to the @dfn{compilation wordlist} (aka current
                   7779: wordlist).
1.1       anton    7780: 
1.36      anton    7781: @cindex wid
                   7782: A word list is identified by a cell-sized word list identifier (@i{wid})
                   7783: in much the same way as a file is identified by a file handle. The
                   7784: numerical value of the wid has no (portable) meaning, and might change
                   7785: from session to session.
1.1       anton    7786: 
1.29      crook    7787: The ANS Forth ``Search order'' word set is intended to provide a set of
                   7788: low-level tools that allow various different schemes to be
1.74      anton    7789: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    7790: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    7791: Forth.
1.1       anton    7792: 
1.27      crook    7793: @comment TODO: locals section refers to here, saying that every word list (aka
                   7794: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    7795: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    7796: 
1.45      crook    7797: @comment TODO: document markers, reveal, tables, mappedwordlist
                   7798: 
                   7799: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    7800: @comment word from the source files, rather than some alias.
1.44      crook    7801: 
1.26      crook    7802: doc-forth-wordlist
                   7803: doc-definitions
                   7804: doc-get-current
                   7805: doc-set-current
                   7806: doc-get-order
1.45      crook    7807: doc---gforthman-set-order
1.26      crook    7808: doc-wordlist
1.30      anton    7809: doc-table
1.79      anton    7810: doc->order
1.36      anton    7811: doc-previous
1.26      crook    7812: doc-also
1.45      crook    7813: doc---gforthman-forth
1.26      crook    7814: doc-only
1.45      crook    7815: doc---gforthman-order
1.15      anton    7816: 
1.26      crook    7817: doc-find
                   7818: doc-search-wordlist
1.15      anton    7819: 
1.26      crook    7820: doc-words
                   7821: doc-vlist
1.44      crook    7822: @c doc-words-deferred
1.1       anton    7823: 
1.74      anton    7824: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    7825: doc-root
                   7826: doc-vocabulary
                   7827: doc-seal
                   7828: doc-vocs
                   7829: doc-current
                   7830: doc-context
1.1       anton    7831: 
1.44      crook    7832: 
1.26      crook    7833: @menu
1.75      anton    7834: * Vocabularies::                
1.67      anton    7835: * Why use word lists?::         
1.75      anton    7836: * Word list example::           
1.26      crook    7837: @end menu
                   7838: 
1.75      anton    7839: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   7840: @subsection Vocabularies
                   7841: @cindex Vocabularies, detailed explanation
                   7842: 
                   7843: Here is an example of creating and using a new wordlist using ANS
                   7844: Forth words:
                   7845: 
                   7846: @example
                   7847: wordlist constant my-new-words-wordlist
                   7848: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   7849: 
                   7850: \ add it to the search order
                   7851: also my-new-words
                   7852: 
                   7853: \ alternatively, add it to the search order and make it
                   7854: \ the compilation word list
                   7855: also my-new-words definitions
                   7856: \ type "order" to see the problem
                   7857: @end example
                   7858: 
                   7859: The problem with this example is that @code{order} has no way to
                   7860: associate the name @code{my-new-words} with the wid of the word list (in
                   7861: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   7862: that has no associated name). There is no Standard way of associating a
                   7863: name with a wid.
                   7864: 
                   7865: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   7866: associates a name with a wid:
                   7867: 
                   7868: @example
                   7869: vocabulary my-new-words
                   7870: 
                   7871: \ add it to the search order
                   7872: also my-new-words
                   7873: 
                   7874: \ alternatively, add it to the search order and make it
                   7875: \ the compilation word list
                   7876: my-new-words definitions
                   7877: \ type "order" to see that the problem is solved
                   7878: @end example
                   7879: 
                   7880: 
                   7881: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    7882: @subsection Why use word lists?
                   7883: @cindex word lists - why use them?
                   7884: 
1.74      anton    7885: Here are some reasons why people use wordlists:
1.26      crook    7886: 
                   7887: @itemize @bullet
1.74      anton    7888: 
                   7889: @c anton: Gforth's hashing implementation makes the search speed
                   7890: @c independent from the number of words.  But it is linear with the number
                   7891: @c of wordlists that have to be searched, so in effect using more wordlists
                   7892: @c actually slows down compilation.
                   7893: 
                   7894: @c @item
                   7895: @c To improve compilation speed by reducing the number of header space
                   7896: @c entries that must be searched. This is achieved by creating a new
                   7897: @c word list that contains all of the definitions that are used in the
                   7898: @c definition of a Forth system but which would not usually be used by
                   7899: @c programs running on that system. That word list would be on the search
                   7900: @c list when the Forth system was compiled but would be removed from the
                   7901: @c search list for normal operation. This can be a useful technique for
                   7902: @c low-performance systems (for example, 8-bit processors in embedded
                   7903: @c systems) but is unlikely to be necessary in high-performance desktop
                   7904: @c systems.
                   7905: 
1.26      crook    7906: @item
                   7907: To prevent a set of words from being used outside the context in which
                   7908: they are valid. Two classic examples of this are an integrated editor
                   7909: (all of the edit commands are defined in a separate word list; the
                   7910: search order is set to the editor word list when the editor is invoked;
                   7911: the old search order is restored when the editor is terminated) and an
                   7912: integrated assembler (the op-codes for the machine are defined in a
                   7913: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    7914: 
                   7915: @item
                   7916: To organize the words of an application or library into a user-visible
                   7917: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   7918: of helper words used just for the implementation (hidden in a separate
1.75      anton    7919: wordlist).  This keeps @code{words}' output smaller, separates
                   7920: implementation and interface, and reduces the chance of name conflicts
                   7921: within the common wordlist.
1.74      anton    7922: 
1.26      crook    7923: @item
                   7924: To prevent a name-space clash between multiple definitions with the same
                   7925: name. For example, when building a cross-compiler you might have a word
                   7926: @code{IF} that generates conditional code for your target system. By
                   7927: placing this definition in a different word list you can control whether
                   7928: the host system's @code{IF} or the target system's @code{IF} get used in
                   7929: any particular context by controlling the order of the word lists on the
                   7930: search order stack.
1.74      anton    7931: 
1.26      crook    7932: @end itemize
1.1       anton    7933: 
1.74      anton    7934: The downsides of using wordlists are:
                   7935: 
                   7936: @itemize
                   7937: 
                   7938: @item
                   7939: Debugging becomes more cumbersome.
                   7940: 
                   7941: @item
                   7942: Name conflicts worked around with wordlists are still there, and you
                   7943: have to arrange the search order carefully to get the desired results;
                   7944: if you forget to do that, you get hard-to-find errors (as in any case
                   7945: where you read the code differently from the compiler; @code{see} can
1.75      anton    7946: help seeing which of several possible words the name resolves to in such
                   7947: cases).  @code{See} displays just the name of the words, not what
                   7948: wordlist they belong to, so it might be misleading.  Using unique names
                   7949: is a better approach to avoid name conflicts.
1.74      anton    7950: 
                   7951: @item
                   7952: You have to explicitly undo any changes to the search order.  In many
                   7953: cases it would be more convenient if this happened implicitly.  Gforth
                   7954: currently does not provide such a feature, but it may do so in the
                   7955: future.
                   7956: @end itemize
                   7957: 
                   7958: 
1.75      anton    7959: @node Word list example,  , Why use word lists?, Word Lists
                   7960: @subsection Word list example
                   7961: @cindex word lists - example
1.1       anton    7962: 
1.74      anton    7963: The following example is from the
                   7964: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   7965: garbage collector} and uses wordlists to separate public words from
                   7966: helper words:
                   7967: 
                   7968: @example
                   7969: get-current ( wid )
                   7970: vocabulary garbage-collector also garbage-collector definitions
                   7971: ... \ define helper words
                   7972: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   7973: ... \ define the public (i.e., API) words
                   7974:     \ they can refer to the helper words
                   7975: previous \ restore original search order (helper words become invisible)
                   7976: @end example
                   7977: 
1.26      crook    7978: @c -------------------------------------------------------------
                   7979: @node Environmental Queries, Files, Word Lists, Words
                   7980: @section Environmental Queries
                   7981: @cindex environmental queries
1.21      crook    7982: 
1.26      crook    7983: ANS Forth introduced the idea of ``environmental queries'' as a way
                   7984: for a program running on a system to determine certain characteristics of the system.
                   7985: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    7986: 
1.32      anton    7987: The Standard requires that the header space used for environmental queries
                   7988: be distinct from the header space used for definitions.
1.21      crook    7989: 
1.26      crook    7990: Typically, environmental queries are supported by creating a set of
1.29      crook    7991: definitions in a word list that is @i{only} used during environmental
1.26      crook    7992: queries; that is what Gforth does. There is no Standard way of adding
                   7993: definitions to the set of recognised environmental queries, but any
                   7994: implementation that supports the loading of optional word sets must have
                   7995: some mechanism for doing this (after loading the word set, the
                   7996: associated environmental query string must return @code{true}). In
                   7997: Gforth, the word list used to honour environmental queries can be
                   7998: manipulated just like any other word list.
1.21      crook    7999: 
1.44      crook    8000: 
1.26      crook    8001: doc-environment?
                   8002: doc-environment-wordlist
1.21      crook    8003: 
1.26      crook    8004: doc-gforth
                   8005: doc-os-class
1.21      crook    8006: 
1.44      crook    8007: 
1.26      crook    8008: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8009: returning two items on the stack, querying it using @code{environment?}
                   8010: will return an additional item; the @code{true} flag that shows that the
                   8011: string was recognised.
1.21      crook    8012: 
1.26      crook    8013: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8014: 
1.26      crook    8015: Here are some examples of using environmental queries:
1.21      crook    8016: 
1.26      crook    8017: @example
                   8018: s" address-unit-bits" environment? 0=
                   8019: [IF]
                   8020:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8021: [ELSE]
                   8022:      drop \ ensure balanced stack effect
1.26      crook    8023: [THEN]
1.21      crook    8024: 
1.75      anton    8025: \ this might occur in the prelude of a standard program that uses THROW
                   8026: s" exception" environment? [IF]
                   8027:    0= [IF]
                   8028:       : throw abort" exception thrown" ;
                   8029:    [THEN]
                   8030: [ELSE] \ we don't know, so make sure
                   8031:    : throw abort" exception thrown" ;
                   8032: [THEN]
1.21      crook    8033: 
1.26      crook    8034: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8035:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8036: 
                   8037: \ a program using v*
                   8038: s" gforth" environment? [IF]
                   8039:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8040:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8041:      >r swap 2swap swap 0e r> 0 ?DO
                   8042:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
                   8043:      LOOP
                   8044:      2drop 2drop ; 
                   8045:   [THEN]
                   8046: [ELSE] \ 
                   8047:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8048:   ...
                   8049: [THEN]
1.26      crook    8050: @end example
1.21      crook    8051: 
1.26      crook    8052: Here is an example of adding a definition to the environment word list:
1.21      crook    8053: 
1.26      crook    8054: @example
                   8055: get-current environment-wordlist set-current
                   8056: true constant block
                   8057: true constant block-ext
                   8058: set-current
                   8059: @end example
1.21      crook    8060: 
1.26      crook    8061: You can see what definitions are in the environment word list like this:
1.21      crook    8062: 
1.26      crook    8063: @example
1.79      anton    8064: environment-wordlist >order words previous
1.26      crook    8065: @end example
1.21      crook    8066: 
                   8067: 
1.26      crook    8068: @c -------------------------------------------------------------
                   8069: @node Files, Blocks, Environmental Queries, Words
                   8070: @section Files
1.28      crook    8071: @cindex files
                   8072: @cindex I/O - file-handling
1.21      crook    8073: 
1.26      crook    8074: Gforth provides facilities for accessing files that are stored in the
                   8075: host operating system's file-system. Files that are processed by Gforth
                   8076: can be divided into two categories:
1.21      crook    8077: 
1.23      crook    8078: @itemize @bullet
                   8079: @item
1.29      crook    8080: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8081: @item
1.29      crook    8082: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8083: @end itemize
                   8084: 
                   8085: @menu
1.48      anton    8086: * Forth source files::          
                   8087: * General files::               
                   8088: * Search Paths::                
1.26      crook    8089: @end menu
                   8090: 
                   8091: @c -------------------------------------------------------------
                   8092: @node Forth source files, General files, Files, Files
                   8093: @subsection Forth source files
                   8094: @cindex including files
                   8095: @cindex Forth source files
1.21      crook    8096: 
1.26      crook    8097: The simplest way to interpret the contents of a file is to use one of
                   8098: these two formats:
1.21      crook    8099: 
1.26      crook    8100: @example
                   8101: include mysource.fs
                   8102: s" mysource.fs" included
                   8103: @end example
1.21      crook    8104: 
1.75      anton    8105: You usually want to include a file only if it is not included already
1.26      crook    8106: (by, say, another source file). In that case, you can use one of these
1.45      crook    8107: three formats:
1.21      crook    8108: 
1.26      crook    8109: @example
                   8110: require mysource.fs
                   8111: needs mysource.fs
                   8112: s" mysource.fs" required
                   8113: @end example
1.21      crook    8114: 
1.26      crook    8115: @cindex stack effect of included files
                   8116: @cindex including files, stack effect
1.45      crook    8117: It is good practice to write your source files such that interpreting them
                   8118: does not change the stack. Source files designed in this way can be used with
1.26      crook    8119: @code{required} and friends without complications. For example:
1.21      crook    8120: 
1.26      crook    8121: @example
1.75      anton    8122: 1024 require foo.fs drop
1.26      crook    8123: @end example
1.21      crook    8124: 
1.75      anton    8125: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8126: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8127: ), which allows its use with @code{require}.  Of course with such
                   8128: parameters to required files, you have to ensure that the first
                   8129: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8130: master load file).
1.44      crook    8131: 
1.26      crook    8132: doc-include-file
                   8133: doc-included
1.28      crook    8134: doc-included?
1.26      crook    8135: doc-include
                   8136: doc-required
                   8137: doc-require
                   8138: doc-needs
1.75      anton    8139: @c doc-init-included-files @c internal
                   8140: doc-sourcefilename
                   8141: doc-sourceline#
1.44      crook    8142: 
1.26      crook    8143: A definition in ANS Forth for @code{required} is provided in
                   8144: @file{compat/required.fs}.
1.21      crook    8145: 
1.26      crook    8146: @c -------------------------------------------------------------
                   8147: @node General files, Search Paths, Forth source files, Files
                   8148: @subsection General files
                   8149: @cindex general files
                   8150: @cindex file-handling
1.21      crook    8151: 
1.75      anton    8152: Files are opened/created by name and type. The following file access
                   8153: methods (FAMs) are recognised:
1.44      crook    8154: 
1.75      anton    8155: @cindex fam (file access method)
1.26      crook    8156: doc-r/o
                   8157: doc-r/w
                   8158: doc-w/o
                   8159: doc-bin
1.1       anton    8160: 
1.44      crook    8161: 
1.26      crook    8162: When a file is opened/created, it returns a file identifier,
1.29      crook    8163: @i{wfileid} that is used for all other file commands. All file
                   8164: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8165: successful operation and an implementation-defined non-zero value in the
                   8166: case of an error.
1.21      crook    8167: 
1.44      crook    8168: 
1.26      crook    8169: doc-open-file
                   8170: doc-create-file
1.21      crook    8171: 
1.26      crook    8172: doc-close-file
                   8173: doc-delete-file
                   8174: doc-rename-file
                   8175: doc-read-file
                   8176: doc-read-line
                   8177: doc-write-file
                   8178: doc-write-line
                   8179: doc-emit-file
                   8180: doc-flush-file
1.21      crook    8181: 
1.26      crook    8182: doc-file-status
                   8183: doc-file-position
                   8184: doc-reposition-file
                   8185: doc-file-size
                   8186: doc-resize-file
1.21      crook    8187: 
1.93      anton    8188: doc-slurp-file
                   8189: doc-slurp-fid
1.112     anton    8190: doc-stdin
                   8191: doc-stdout
                   8192: doc-stderr
1.44      crook    8193: 
1.26      crook    8194: @c ---------------------------------------------------------
1.48      anton    8195: @node Search Paths,  , General files, Files
1.26      crook    8196: @subsection Search Paths
                   8197: @cindex path for @code{included}
                   8198: @cindex file search path
                   8199: @cindex @code{include} search path
                   8200: @cindex search path for files
1.21      crook    8201: 
1.26      crook    8202: If you specify an absolute filename (i.e., a filename starting with
                   8203: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8204: @samp{C:...})) for @code{included} and friends, that file is included
                   8205: just as you would expect.
1.21      crook    8206: 
1.75      anton    8207: If the filename starts with @file{./}, this refers to the directory that
                   8208: the present file was @code{included} from.  This allows files to include
                   8209: other files relative to their own position (irrespective of the current
                   8210: working directory or the absolute position).  This feature is essential
                   8211: for libraries consisting of several files, where a file may include
                   8212: other files from the library.  It corresponds to @code{#include "..."}
                   8213: in C. If the current input source is not a file, @file{.} refers to the
                   8214: directory of the innermost file being included, or, if there is no file
                   8215: being included, to the current working directory.
                   8216: 
                   8217: For relative filenames (not starting with @file{./}), Gforth uses a
                   8218: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8219: tries to find the given filename in the directories present in the path,
                   8220: and includes the first one it finds. There are separate search paths for
                   8221: Forth source files and general files.  If the search path contains the
                   8222: directory @file{.}, this refers to the directory of the current file, or
                   8223: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8224: 
1.26      crook    8225: Use @file{~+} to refer to the current working directory (as in the
                   8226: @code{bash}).
1.1       anton    8227: 
1.75      anton    8228: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8229: 
1.48      anton    8230: @menu
1.75      anton    8231: * Source Search Paths::         
1.48      anton    8232: * General Search Paths::        
                   8233: @end menu
                   8234: 
1.26      crook    8235: @c ---------------------------------------------------------
1.75      anton    8236: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8237: @subsubsection Source Search Paths
                   8238: @cindex search path control, source files
1.5       anton    8239: 
1.26      crook    8240: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8241: Gforth}). You can display it and change it using @code{fpath} in
                   8242: combination with the general path handling words.
1.5       anton    8243: 
1.75      anton    8244: doc-fpath
                   8245: @c the functionality of the following words is easily available through
                   8246: @c   fpath and the general path words.  The may go away.
                   8247: @c doc-.fpath
                   8248: @c doc-fpath+
                   8249: @c doc-fpath=
                   8250: @c doc-open-fpath-file
1.44      crook    8251: 
                   8252: @noindent
1.26      crook    8253: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8254: 
1.26      crook    8255: @example
1.75      anton    8256: fpath path= /usr/lib/forth/|./
1.26      crook    8257: require timer.fs
                   8258: @end example
1.5       anton    8259: 
1.75      anton    8260: 
1.26      crook    8261: @c ---------------------------------------------------------
1.75      anton    8262: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8263: @subsubsection General Search Paths
1.75      anton    8264: @cindex search path control, source files
1.5       anton    8265: 
1.26      crook    8266: Your application may need to search files in several directories, like
                   8267: @code{included} does. To facilitate this, Gforth allows you to define
                   8268: and use your own search paths, by providing generic equivalents of the
                   8269: Forth search path words:
1.5       anton    8270: 
1.75      anton    8271: doc-open-path-file
                   8272: doc-path-allot
                   8273: doc-clear-path
                   8274: doc-also-path
1.26      crook    8275: doc-.path
                   8276: doc-path+
                   8277: doc-path=
1.5       anton    8278: 
1.75      anton    8279: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8280: 
1.75      anton    8281: Here's an example of creating an empty search path:
                   8282: @c
1.26      crook    8283: @example
1.75      anton    8284: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8285: @end example
1.5       anton    8286: 
1.26      crook    8287: @c -------------------------------------------------------------
                   8288: @node Blocks, Other I/O, Files, Words
                   8289: @section Blocks
1.28      crook    8290: @cindex I/O - blocks
                   8291: @cindex blocks
                   8292: 
                   8293: When you run Gforth on a modern desk-top computer, it runs under the
                   8294: control of an operating system which provides certain services.  One of
                   8295: these services is @var{file services}, which allows Forth source code
                   8296: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8297: 
                   8298: Traditionally, Forth has been an important programming language on
                   8299: systems where it has interfaced directly to the underlying hardware with
                   8300: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8301: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8302: 
                   8303: A block is a 1024-byte data area, which can be used to hold data or
                   8304: Forth source code. No structure is imposed on the contents of the
                   8305: block. A block is identified by its number; blocks are numbered
                   8306: contiguously from 1 to an implementation-defined maximum.
                   8307: 
                   8308: A typical system that used blocks but no operating system might use a
                   8309: single floppy-disk drive for mass storage, with the disks formatted to
                   8310: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8311: first four sectors of the disk to block 1, the second four sectors to
                   8312: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8313: would not contain any file system information, just the set of blocks.
                   8314: 
1.29      crook    8315: @cindex blocks file
1.28      crook    8316: On systems that do provide file services, blocks are typically
1.29      crook    8317: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8318: file}.  The size of the blocks file will be an exact multiple of 1024
                   8319: bytes, corresponding to the number of blocks it contains. This is the
                   8320: mechanism that Gforth uses.
                   8321: 
1.29      crook    8322: @cindex @file{blocks.fb}
1.75      anton    8323: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8324: having specified a blocks file, Gforth defaults to the blocks file
                   8325: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8326: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8327: 
1.29      crook    8328: @cindex block buffers
1.28      crook    8329: When you read and write blocks under program control, Gforth uses a
1.29      crook    8330: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8331: not used when you use @code{load} to interpret the contents of a block.
                   8332: 
1.75      anton    8333: The behaviour of the block buffers is analagous to that of a cache.
                   8334: Each block buffer has three states:
1.28      crook    8335: 
                   8336: @itemize @bullet
                   8337: @item
                   8338: Unassigned
                   8339: @item
                   8340: Assigned-clean
                   8341: @item
                   8342: Assigned-dirty
                   8343: @end itemize
                   8344: 
1.29      crook    8345: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8346: block, the block (specified by its block number) must be assigned to a
                   8347: block buffer.
                   8348: 
                   8349: The assignment of a block to a block buffer is performed by @code{block}
                   8350: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8351: contents of a block. Use @code{buffer} when you don't care about the
                   8352: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8353: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8354: with the particular block is already stored in a block buffer due to an
                   8355: earlier @code{block} command, @code{buffer} will return that block
                   8356: buffer and the existing contents of the block will be
                   8357: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8358: block buffer for the block.}.
1.28      crook    8359: 
1.47      crook    8360: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8361: @code{buffer}, that block buffer becomes the @i{current block
                   8362: buffer}. Data may only be manipulated (read or written) within the
                   8363: current block buffer.
1.47      crook    8364: 
                   8365: When the contents of the current block buffer has been modified it is
1.48      anton    8366: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8367: either abandon the changes (by doing nothing) or mark the block as
                   8368: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8369: not change the blocks file; it simply changes a block buffer's state to
                   8370: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8371: buffer is needed for another block, or explicitly by @code{flush} or
                   8372: @code{save-buffers}.
                   8373: 
                   8374: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8375: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8376: @code{flush}.
1.28      crook    8377: 
1.29      crook    8378: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8379: algorithm to assign a block buffer to a block. That means that any
                   8380: particular block can only be assigned to one specific block buffer,
1.29      crook    8381: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8382: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8383: the new block immediately. If it is @i{assigned-dirty} its current
                   8384: contents are written back to the blocks file on disk before it is
1.28      crook    8385: allocated to the new block.
                   8386: 
                   8387: Although no structure is imposed on the contents of a block, it is
                   8388: traditional to display the contents as 16 lines each of 64 characters.  A
                   8389: block provides a single, continuous stream of input (for example, it
                   8390: acts as a single parse area) -- there are no end-of-line characters
                   8391: within a block, and no end-of-file character at the end of a
                   8392: block. There are two consequences of this:
1.26      crook    8393: 
1.28      crook    8394: @itemize @bullet
                   8395: @item
                   8396: The last character of one line wraps straight into the first character
                   8397: of the following line
                   8398: @item
                   8399: The word @code{\} -- comment to end of line -- requires special
                   8400: treatment; in the context of a block it causes all characters until the
                   8401: end of the current 64-character ``line'' to be ignored.
                   8402: @end itemize
                   8403: 
                   8404: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8405: the current blocks file will be extended to the appropriate size and the
1.28      crook    8406: block buffer will be initialised with spaces.
                   8407: 
1.47      crook    8408: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8409: for details) but doesn't encourage the use of blocks; the mechanism is
                   8410: only provided for backward compatibility -- ANS Forth requires blocks to
                   8411: be available when files are.
1.28      crook    8412: 
                   8413: Common techniques that are used when working with blocks include:
                   8414: 
                   8415: @itemize @bullet
                   8416: @item
                   8417: A screen editor that allows you to edit blocks without leaving the Forth
                   8418: environment.
                   8419: @item
                   8420: Shadow screens; where every code block has an associated block
                   8421: containing comments (for example: code in odd block numbers, comments in
                   8422: even block numbers). Typically, the block editor provides a convenient
                   8423: mechanism to toggle between code and comments.
                   8424: @item
                   8425: Load blocks; a single block (typically block 1) contains a number of
                   8426: @code{thru} commands which @code{load} the whole of the application.
                   8427: @end itemize
1.26      crook    8428: 
1.29      crook    8429: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8430: integrated into a Forth programming environment.
1.26      crook    8431: 
                   8432: @comment TODO what about errors on open-blocks?
1.44      crook    8433: 
1.26      crook    8434: doc-open-blocks
                   8435: doc-use
1.75      anton    8436: doc-block-offset
1.26      crook    8437: doc-get-block-fid
                   8438: doc-block-position
1.28      crook    8439: 
1.75      anton    8440: doc-list
1.28      crook    8441: doc-scr
                   8442: 
1.45      crook    8443: doc---gforthman-block
1.28      crook    8444: doc-buffer
                   8445: 
1.75      anton    8446: doc-empty-buffers
                   8447: doc-empty-buffer
1.26      crook    8448: doc-update
1.28      crook    8449: doc-updated?
1.26      crook    8450: doc-save-buffers
1.75      anton    8451: doc-save-buffer
1.26      crook    8452: doc-flush
1.28      crook    8453: 
1.26      crook    8454: doc-load
                   8455: doc-thru
                   8456: doc-+load
                   8457: doc-+thru
1.45      crook    8458: doc---gforthman--->
1.26      crook    8459: doc-block-included
                   8460: 
1.44      crook    8461: 
1.26      crook    8462: @c -------------------------------------------------------------
1.78      anton    8463: @node Other I/O, Locals, Blocks, Words
1.26      crook    8464: @section Other I/O
1.28      crook    8465: @cindex I/O - keyboard and display
1.26      crook    8466: 
                   8467: @menu
                   8468: * Simple numeric output::       Predefined formats
                   8469: * Formatted numeric output::    Formatted (pictured) output
                   8470: * String Formats::              How Forth stores strings in memory
1.67      anton    8471: * Displaying characters and strings::  Other stuff
1.26      crook    8472: * Input::                       Input
1.112     anton    8473: * Pipes::                       How to create your own pipes
1.26      crook    8474: @end menu
                   8475: 
                   8476: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8477: @subsection Simple numeric output
1.28      crook    8478: @cindex numeric output - simple/free-format
1.5       anton    8479: 
1.26      crook    8480: The simplest output functions are those that display numbers from the
                   8481: data or floating-point stacks. Floating-point output is always displayed
                   8482: using base 10. Numbers displayed from the data stack use the value stored
                   8483: in @code{base}.
1.5       anton    8484: 
1.44      crook    8485: 
1.26      crook    8486: doc-.
                   8487: doc-dec.
                   8488: doc-hex.
                   8489: doc-u.
                   8490: doc-.r
                   8491: doc-u.r
                   8492: doc-d.
                   8493: doc-ud.
                   8494: doc-d.r
                   8495: doc-ud.r
                   8496: doc-f.
                   8497: doc-fe.
                   8498: doc-fs.
1.111     anton    8499: doc-f.rdp
1.44      crook    8500: 
1.26      crook    8501: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8502: formats are shown below:
1.5       anton    8503: 
                   8504: @example
1.26      crook    8505: f. 123456779999999000000000000.
                   8506: fe. 123.456779999999E24
                   8507: fs. 1.23456779999999E26
1.5       anton    8508: @end example
                   8509: 
                   8510: 
1.26      crook    8511: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8512: @subsection Formatted numeric output
1.28      crook    8513: @cindex formatted numeric output
1.26      crook    8514: @cindex pictured numeric output
1.28      crook    8515: @cindex numeric output - formatted
1.26      crook    8516: 
1.29      crook    8517: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8518: output} for formatted printing of integers.  In this technique, digits
                   8519: are extracted from the number (using the current output radix defined by
                   8520: @code{base}), converted to ASCII codes and appended to a string that is
                   8521: built in a scratch-pad area of memory (@pxref{core-idef,
                   8522: Implementation-defined options, Implementation-defined
                   8523: options}). Arbitrary characters can be appended to the string during the
                   8524: extraction process. The completed string is specified by an address
                   8525: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8526: under program control.
1.5       anton    8527: 
1.75      anton    8528: All of the integer output words described in the previous section
                   8529: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8530: numeric output.
1.5       anton    8531: 
1.47      crook    8532: Three important things to remember about pictured numeric output:
1.5       anton    8533: 
1.26      crook    8534: @itemize @bullet
                   8535: @item
1.28      crook    8536: It always operates on double-precision numbers; to display a
1.49      anton    8537: single-precision number, convert it first (for ways of doing this
                   8538: @pxref{Double precision}).
1.26      crook    8539: @item
1.28      crook    8540: It always treats the double-precision number as though it were
                   8541: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8542: @item
                   8543: The string is built up from right to left; least significant digit first.
                   8544: @end itemize
1.5       anton    8545: 
1.44      crook    8546: 
1.26      crook    8547: doc-<#
1.47      crook    8548: doc-<<#
1.26      crook    8549: doc-#
                   8550: doc-#s
                   8551: doc-hold
                   8552: doc-sign
                   8553: doc-#>
1.47      crook    8554: doc-#>>
1.5       anton    8555: 
1.26      crook    8556: doc-represent
1.111     anton    8557: doc-f>str-rdp
                   8558: doc-f>buf-rdp
1.5       anton    8559: 
1.44      crook    8560: 
                   8561: @noindent
1.26      crook    8562: Here are some examples of using pictured numeric output:
1.5       anton    8563: 
                   8564: @example
1.26      crook    8565: : my-u. ( u -- )
                   8566:   \ Simplest use of pns.. behaves like Standard u. 
                   8567:   0              \ convert to unsigned double
1.75      anton    8568:   <<#            \ start conversion
1.26      crook    8569:   #s             \ convert all digits
                   8570:   #>             \ complete conversion
1.75      anton    8571:   TYPE SPACE     \ display, with trailing space
                   8572:   #>> ;          \ release hold area
1.5       anton    8573: 
1.26      crook    8574: : cents-only ( u -- )
                   8575:   0              \ convert to unsigned double
1.75      anton    8576:   <<#            \ start conversion
1.26      crook    8577:   # #            \ convert two least-significant digits
                   8578:   #>             \ complete conversion, discard other digits
1.75      anton    8579:   TYPE SPACE     \ display, with trailing space
                   8580:   #>> ;          \ release hold area
1.5       anton    8581: 
1.26      crook    8582: : dollars-and-cents ( u -- )
                   8583:   0              \ convert to unsigned double
1.75      anton    8584:   <<#            \ start conversion
1.26      crook    8585:   # #            \ convert two least-significant digits
                   8586:   [char] . hold  \ insert decimal point
                   8587:   #s             \ convert remaining digits
                   8588:   [char] $ hold  \ append currency symbol
                   8589:   #>             \ complete conversion
1.75      anton    8590:   TYPE SPACE     \ display, with trailing space
                   8591:   #>> ;          \ release hold area
1.5       anton    8592: 
1.26      crook    8593: : my-. ( n -- )
                   8594:   \ handling negatives.. behaves like Standard .
                   8595:   s>d            \ convert to signed double
                   8596:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8597:   <<#            \ start conversion
1.26      crook    8598:   #s             \ convert all digits
                   8599:   rot sign       \ get at sign byte, append "-" if needed
                   8600:   #>             \ complete conversion
1.75      anton    8601:   TYPE SPACE     \ display, with trailing space
                   8602:   #>> ;          \ release hold area
1.5       anton    8603: 
1.26      crook    8604: : account. ( n -- )
1.75      anton    8605:   \ accountants don't like minus signs, they use parentheses
1.26      crook    8606:   \ for negative numbers
                   8607:   s>d            \ convert to signed double
                   8608:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8609:   <<#            \ start conversion
1.26      crook    8610:   2 pick         \ get copy of sign byte
                   8611:   0< IF [char] ) hold THEN \ right-most character of output
                   8612:   #s             \ convert all digits
                   8613:   rot            \ get at sign byte
                   8614:   0< IF [char] ( hold THEN
                   8615:   #>             \ complete conversion
1.75      anton    8616:   TYPE SPACE     \ display, with trailing space
                   8617:   #>> ;          \ release hold area
                   8618: 
1.5       anton    8619: @end example
                   8620: 
1.26      crook    8621: Here are some examples of using these words:
1.5       anton    8622: 
                   8623: @example
1.26      crook    8624: 1 my-u. 1
                   8625: hex -1 my-u. decimal FFFFFFFF
                   8626: 1 cents-only 01
                   8627: 1234 cents-only 34
                   8628: 2 dollars-and-cents $0.02
                   8629: 1234 dollars-and-cents $12.34
                   8630: 123 my-. 123
                   8631: -123 my. -123
                   8632: 123 account. 123
                   8633: -456 account. (456)
1.5       anton    8634: @end example
                   8635: 
                   8636: 
1.26      crook    8637: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8638: @subsection String Formats
1.27      crook    8639: @cindex strings - see character strings
                   8640: @cindex character strings - formats
1.28      crook    8641: @cindex I/O - see character strings
1.75      anton    8642: @cindex counted strings
                   8643: 
                   8644: @c anton: this does not really belong here; maybe the memory section,
                   8645: @c  or the principles chapter
1.26      crook    8646: 
1.27      crook    8647: Forth commonly uses two different methods for representing character
                   8648: strings:
1.26      crook    8649: 
                   8650: @itemize @bullet
                   8651: @item
                   8652: @cindex address of counted string
1.45      crook    8653: @cindex counted string
1.29      crook    8654: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8655: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8656: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8657: memory.
                   8658: @item
1.29      crook    8659: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8660: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8661: first byte of the string.
                   8662: @end itemize
                   8663: 
                   8664: ANS Forth encourages the use of the second format when representing
1.75      anton    8665: strings.
1.26      crook    8666: 
1.44      crook    8667: 
1.26      crook    8668: doc-count
                   8669: 
1.44      crook    8670: 
1.49      anton    8671: For words that move, copy and search for strings see @ref{Memory
                   8672: Blocks}. For words that display characters and strings see
                   8673: @ref{Displaying characters and strings}.
1.26      crook    8674: 
                   8675: @node Displaying characters and strings, Input, String Formats, Other I/O
                   8676: @subsection Displaying characters and strings
1.27      crook    8677: @cindex characters - compiling and displaying
                   8678: @cindex character strings - compiling and displaying
1.26      crook    8679: 
                   8680: This section starts with a glossary of Forth words and ends with a set
                   8681: of examples.
                   8682: 
1.44      crook    8683: 
1.26      crook    8684: doc-bl
                   8685: doc-space
                   8686: doc-spaces
                   8687: doc-emit
                   8688: doc-toupper
                   8689: doc-."
                   8690: doc-.(
1.98      anton    8691: doc-.\"
1.26      crook    8692: doc-type
1.44      crook    8693: doc-typewhite
1.26      crook    8694: doc-cr
1.27      crook    8695: @cindex cursor control
1.26      crook    8696: doc-at-xy
                   8697: doc-page
                   8698: doc-s"
1.98      anton    8699: doc-s\"
1.26      crook    8700: doc-c"
                   8701: doc-char
                   8702: doc-[char]
                   8703: 
1.44      crook    8704: 
                   8705: @noindent
1.26      crook    8706: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8707: 
                   8708: @example
1.26      crook    8709: .( text-1)
                   8710: : my-word
                   8711:   ." text-2" cr
                   8712:   .( text-3)
                   8713: ;
                   8714: 
                   8715: ." text-4"
                   8716: 
                   8717: : my-char
                   8718:   [char] ALPHABET emit
                   8719:   char emit
                   8720: ;
1.5       anton    8721: @end example
                   8722: 
1.26      crook    8723: When you load this code into Gforth, the following output is generated:
1.5       anton    8724: 
1.26      crook    8725: @example
1.30      anton    8726: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    8727: @end example
1.5       anton    8728: 
1.26      crook    8729: @itemize @bullet
                   8730: @item
                   8731: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   8732: is an immediate word; it behaves in the same way whether it is used inside
                   8733: or outside a colon definition.
                   8734: @item
                   8735: Message @code{text-4} is displayed because of Gforth's added interpretation
                   8736: semantics for @code{."}.
                   8737: @item
1.29      crook    8738: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    8739: performs the compilation semantics for @code{."} within the definition of
                   8740: @code{my-word}.
                   8741: @end itemize
1.5       anton    8742: 
1.26      crook    8743: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    8744: 
1.26      crook    8745: @example
1.30      anton    8746: @kbd{my-word @key{RET}} text-2
1.26      crook    8747:  ok
1.30      anton    8748: @kbd{my-char fred @key{RET}} Af ok
                   8749: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    8750: @end example
1.5       anton    8751: 
                   8752: @itemize @bullet
                   8753: @item
1.26      crook    8754: Message @code{text-2} is displayed because of the run-time behaviour of
                   8755: @code{."}.
                   8756: @item
                   8757: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   8758: on the stack at run-time. @code{emit} always displays the character
                   8759: when @code{my-char} is executed.
                   8760: @item
                   8761: @code{char} parses a string at run-time and the second @code{emit} displays
                   8762: the first character of the string.
1.5       anton    8763: @item
1.26      crook    8764: If you type @code{see my-char} you can see that @code{[char]} discarded
                   8765: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   8766: definition of @code{my-char}.
1.5       anton    8767: @end itemize
                   8768: 
                   8769: 
                   8770: 
1.112     anton    8771: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26      crook    8772: @subsection Input
                   8773: @cindex input
1.28      crook    8774: @cindex I/O - see input
                   8775: @cindex parsing a string
1.5       anton    8776: 
1.49      anton    8777: For ways of storing character strings in memory see @ref{String Formats}.
1.5       anton    8778: 
1.27      crook    8779: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    8780: @comment then index them
1.27      crook    8781: 
1.44      crook    8782: 
1.27      crook    8783: doc-key
                   8784: doc-key?
1.45      crook    8785: doc-ekey
                   8786: doc-ekey?
                   8787: doc-ekey>char
1.26      crook    8788: doc->number
                   8789: doc->float
                   8790: doc-accept
1.109     anton    8791: doc-edit-line
1.27      crook    8792: doc-pad
                   8793: @comment obsolescent words..
                   8794: doc-convert
1.26      crook    8795: doc-expect
1.27      crook    8796: doc-span
1.5       anton    8797: 
                   8798: 
1.112     anton    8799: @node Pipes,  , Input, Other I/O
                   8800: @subsection Pipes
                   8801: @cindex pipes, creating your own
                   8802: 
                   8803: In addition to using Gforth in pipes created by other processes
                   8804: (@pxref{Gforth in pipes}), you can create your own pipe with
                   8805: @code{open-pipe}, and read from or write to it.
                   8806: 
                   8807: doc-open-pipe
                   8808: doc-close-pipe
                   8809: 
                   8810: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
                   8811: you don't catch this exception, Gforth will catch it and exit, usually
                   8812: silently (@pxref{Gforth in pipes}).  Since you probably do not want
                   8813: this, you should wrap a @code{catch} or @code{try} block around the code
                   8814: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
                   8815: problem yourself, and then return to regular processing.
                   8816: 
                   8817: doc-broken-pipe-error
                   8818: 
                   8819: 
1.78      anton    8820: @c -------------------------------------------------------------
                   8821: @node Locals, Structures, Other I/O, Words
                   8822: @section Locals
                   8823: @cindex locals
                   8824: 
                   8825: Local variables can make Forth programming more enjoyable and Forth
                   8826: programs easier to read. Unfortunately, the locals of ANS Forth are
                   8827: laden with restrictions. Therefore, we provide not only the ANS Forth
                   8828: locals wordset, but also our own, more powerful locals wordset (we
                   8829: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    8830: 
1.78      anton    8831: The ideas in this section have also been published in M. Anton Ertl,
                   8832: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   8833: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    8834: 
                   8835: @menu
1.78      anton    8836: * Gforth locals::               
                   8837: * ANS Forth locals::            
1.5       anton    8838: @end menu
                   8839: 
1.78      anton    8840: @node Gforth locals, ANS Forth locals, Locals, Locals
                   8841: @subsection Gforth locals
                   8842: @cindex Gforth locals
                   8843: @cindex locals, Gforth style
1.5       anton    8844: 
1.78      anton    8845: Locals can be defined with
1.44      crook    8846: 
1.78      anton    8847: @example
                   8848: @{ local1 local2 ... -- comment @}
                   8849: @end example
                   8850: or
                   8851: @example
                   8852: @{ local1 local2 ... @}
                   8853: @end example
1.5       anton    8854: 
1.78      anton    8855: E.g.,
                   8856: @example
                   8857: : max @{ n1 n2 -- n3 @}
                   8858:  n1 n2 > if
                   8859:    n1
                   8860:  else
                   8861:    n2
                   8862:  endif ;
                   8863: @end example
1.44      crook    8864: 
1.78      anton    8865: The similarity of locals definitions with stack comments is intended. A
                   8866: locals definition often replaces the stack comment of a word. The order
                   8867: of the locals corresponds to the order in a stack comment and everything
                   8868: after the @code{--} is really a comment.
1.77      anton    8869: 
1.78      anton    8870: This similarity has one disadvantage: It is too easy to confuse locals
                   8871: declarations with stack comments, causing bugs and making them hard to
                   8872: find. However, this problem can be avoided by appropriate coding
                   8873: conventions: Do not use both notations in the same program. If you do,
                   8874: they should be distinguished using additional means, e.g. by position.
1.77      anton    8875: 
1.78      anton    8876: @cindex types of locals
                   8877: @cindex locals types
                   8878: The name of the local may be preceded by a type specifier, e.g.,
                   8879: @code{F:} for a floating point value:
1.5       anton    8880: 
1.78      anton    8881: @example
                   8882: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   8883: \ complex multiplication
                   8884:  Ar Br f* Ai Bi f* f-
                   8885:  Ar Bi f* Ai Br f* f+ ;
                   8886: @end example
1.44      crook    8887: 
1.78      anton    8888: @cindex flavours of locals
                   8889: @cindex locals flavours
                   8890: @cindex value-flavoured locals
                   8891: @cindex variable-flavoured locals
                   8892: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   8893: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   8894: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   8895: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   8896: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   8897: produces its address (which becomes invalid when the variable's scope is
                   8898: left). E.g., the standard word @code{emit} can be defined in terms of
                   8899: @code{type} like this:
1.5       anton    8900: 
1.78      anton    8901: @example
                   8902: : emit @{ C^ char* -- @}
                   8903:     char* 1 type ;
                   8904: @end example
1.5       anton    8905: 
1.78      anton    8906: @cindex default type of locals
                   8907: @cindex locals, default type
                   8908: A local without type specifier is a @code{W:} local. Both flavours of
                   8909: locals are initialized with values from the data or FP stack.
1.44      crook    8910: 
1.78      anton    8911: Currently there is no way to define locals with user-defined data
                   8912: structures, but we are working on it.
1.5       anton    8913: 
1.78      anton    8914: Gforth allows defining locals everywhere in a colon definition. This
                   8915: poses the following questions:
1.5       anton    8916: 
1.78      anton    8917: @menu
                   8918: * Where are locals visible by name?::  
                   8919: * How long do locals live?::    
                   8920: * Locals programming style::    
                   8921: * Locals implementation::       
                   8922: @end menu
1.44      crook    8923: 
1.78      anton    8924: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   8925: @subsubsection Where are locals visible by name?
                   8926: @cindex locals visibility
                   8927: @cindex visibility of locals
                   8928: @cindex scope of locals
1.5       anton    8929: 
1.78      anton    8930: Basically, the answer is that locals are visible where you would expect
                   8931: it in block-structured languages, and sometimes a little longer. If you
                   8932: want to restrict the scope of a local, enclose its definition in
                   8933: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    8934: 
                   8935: 
1.78      anton    8936: doc-scope
                   8937: doc-endscope
1.5       anton    8938: 
                   8939: 
1.78      anton    8940: These words behave like control structure words, so you can use them
                   8941: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   8942: arbitrary ways.
1.77      anton    8943: 
1.78      anton    8944: If you want a more exact answer to the visibility question, here's the
                   8945: basic principle: A local is visible in all places that can only be
                   8946: reached through the definition of the local@footnote{In compiler
                   8947: construction terminology, all places dominated by the definition of the
                   8948: local.}. In other words, it is not visible in places that can be reached
                   8949: without going through the definition of the local. E.g., locals defined
                   8950: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   8951: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   8952: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    8953: 
1.78      anton    8954: The reasoning behind this solution is: We want to have the locals
                   8955: visible as long as it is meaningful. The user can always make the
                   8956: visibility shorter by using explicit scoping. In a place that can
                   8957: only be reached through the definition of a local, the meaning of a
                   8958: local name is clear. In other places it is not: How is the local
                   8959: initialized at the control flow path that does not contain the
                   8960: definition? Which local is meant, if the same name is defined twice in
                   8961: two independent control flow paths?
1.77      anton    8962: 
1.78      anton    8963: This should be enough detail for nearly all users, so you can skip the
                   8964: rest of this section. If you really must know all the gory details and
                   8965: options, read on.
1.77      anton    8966: 
1.78      anton    8967: In order to implement this rule, the compiler has to know which places
                   8968: are unreachable. It knows this automatically after @code{AHEAD},
                   8969: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   8970: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   8971: compiler that the control flow never reaches that place. If
                   8972: @code{UNREACHABLE} is not used where it could, the only consequence is
                   8973: that the visibility of some locals is more limited than the rule above
                   8974: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   8975: lie to the compiler), buggy code will be produced.
1.77      anton    8976: 
1.5       anton    8977: 
1.78      anton    8978: doc-unreachable
1.5       anton    8979: 
1.23      crook    8980: 
1.78      anton    8981: Another problem with this rule is that at @code{BEGIN}, the compiler
                   8982: does not know which locals will be visible on the incoming
                   8983: back-edge. All problems discussed in the following are due to this
                   8984: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   8985: loops as examples; the discussion also applies to @code{?DO} and other
                   8986: loops). Perhaps the most insidious example is:
1.26      crook    8987: @example
1.78      anton    8988: AHEAD
                   8989: BEGIN
                   8990:   x
                   8991: [ 1 CS-ROLL ] THEN
                   8992:   @{ x @}
                   8993:   ...
                   8994: UNTIL
1.26      crook    8995: @end example
1.23      crook    8996: 
1.78      anton    8997: This should be legal according to the visibility rule. The use of
                   8998: @code{x} can only be reached through the definition; but that appears
                   8999: textually below the use.
                   9000: 
                   9001: From this example it is clear that the visibility rules cannot be fully
                   9002: implemented without major headaches. Our implementation treats common
                   9003: cases as advertised and the exceptions are treated in a safe way: The
                   9004: compiler makes a reasonable guess about the locals visible after a
                   9005: @code{BEGIN}; if it is too pessimistic, the
                   9006: user will get a spurious error about the local not being defined; if the
                   9007: compiler is too optimistic, it will notice this later and issue a
                   9008: warning. In the case above the compiler would complain about @code{x}
                   9009: being undefined at its use. You can see from the obscure examples in
                   9010: this section that it takes quite unusual control structures to get the
                   9011: compiler into trouble, and even then it will often do fine.
1.23      crook    9012: 
1.78      anton    9013: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9014: is that all locals visible before the @code{BEGIN} will also be
                   9015: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9016: are entered only through the @code{BEGIN}, in particular, for normal
                   9017: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9018: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9019: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9020: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9021: warns the user if it was too optimistic:
1.26      crook    9022: @example
1.78      anton    9023: IF
                   9024:   @{ x @}
                   9025: BEGIN
                   9026:   \ x ? 
                   9027: [ 1 cs-roll ] THEN
                   9028:   ...
                   9029: UNTIL
1.26      crook    9030: @end example
1.23      crook    9031: 
1.78      anton    9032: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9033: optimistically assumes that it lives until the @code{THEN}. It notices
                   9034: this difference when it compiles the @code{UNTIL} and issues a
                   9035: warning. The user can avoid the warning, and make sure that @code{x}
                   9036: is not used in the wrong area by using explicit scoping:
                   9037: @example
                   9038: IF
                   9039:   SCOPE
                   9040:   @{ x @}
                   9041:   ENDSCOPE
                   9042: BEGIN
                   9043: [ 1 cs-roll ] THEN
                   9044:   ...
                   9045: UNTIL
                   9046: @end example
1.23      crook    9047: 
1.78      anton    9048: Since the guess is optimistic, there will be no spurious error messages
                   9049: about undefined locals.
1.44      crook    9050: 
1.78      anton    9051: If the @code{BEGIN} is not reachable from above (e.g., after
                   9052: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9053: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9054: defined later. Therefore, the compiler assumes that no locals are
                   9055: visible after the @code{BEGIN}. However, the user can use
                   9056: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9057: visible at the BEGIN as at the point where the top control-flow stack
                   9058: item was created.
1.23      crook    9059: 
1.44      crook    9060: 
1.78      anton    9061: doc-assume-live
1.26      crook    9062: 
1.23      crook    9063: 
1.78      anton    9064: @noindent
                   9065: E.g.,
                   9066: @example
                   9067: @{ x @}
                   9068: AHEAD
                   9069: ASSUME-LIVE
                   9070: BEGIN
                   9071:   x
                   9072: [ 1 CS-ROLL ] THEN
                   9073:   ...
                   9074: UNTIL
                   9075: @end example
1.44      crook    9076: 
1.78      anton    9077: Other cases where the locals are defined before the @code{BEGIN} can be
                   9078: handled by inserting an appropriate @code{CS-ROLL} before the
                   9079: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9080: behind the @code{ASSUME-LIVE}).
1.23      crook    9081: 
1.78      anton    9082: Cases where locals are defined after the @code{BEGIN} (but should be
                   9083: visible immediately after the @code{BEGIN}) can only be handled by
                   9084: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9085: arranged into:
                   9086: @example
                   9087: BEGIN
                   9088:   @{ x @}
                   9089:   ... 0=
                   9090: WHILE
                   9091:   x
                   9092: REPEAT
                   9093: @end example
1.44      crook    9094: 
1.78      anton    9095: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9096: @subsubsection How long do locals live?
                   9097: @cindex locals lifetime
                   9098: @cindex lifetime of locals
1.23      crook    9099: 
1.78      anton    9100: The right answer for the lifetime question would be: A local lives at
                   9101: least as long as it can be accessed. For a value-flavoured local this
                   9102: means: until the end of its visibility. However, a variable-flavoured
                   9103: local could be accessed through its address far beyond its visibility
                   9104: scope. Ultimately, this would mean that such locals would have to be
                   9105: garbage collected. Since this entails un-Forth-like implementation
                   9106: complexities, I adopted the same cowardly solution as some other
                   9107: languages (e.g., C): The local lives only as long as it is visible;
                   9108: afterwards its address is invalid (and programs that access it
                   9109: afterwards are erroneous).
1.23      crook    9110: 
1.78      anton    9111: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9112: @subsubsection Locals programming style
                   9113: @cindex locals programming style
                   9114: @cindex programming style, locals
1.23      crook    9115: 
1.78      anton    9116: The freedom to define locals anywhere has the potential to change
                   9117: programming styles dramatically. In particular, the need to use the
                   9118: return stack for intermediate storage vanishes. Moreover, all stack
                   9119: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9120: determined arguments) can be eliminated: If the stack items are in the
                   9121: wrong order, just write a locals definition for all of them; then
                   9122: write the items in the order you want.
1.23      crook    9123: 
1.78      anton    9124: This seems a little far-fetched and eliminating stack manipulations is
                   9125: unlikely to become a conscious programming objective. Still, the number
                   9126: of stack manipulations will be reduced dramatically if local variables
                   9127: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9128: a traditional implementation of @code{max}).
1.23      crook    9129: 
1.78      anton    9130: This shows one potential benefit of locals: making Forth programs more
                   9131: readable. Of course, this benefit will only be realized if the
                   9132: programmers continue to honour the principle of factoring instead of
                   9133: using the added latitude to make the words longer.
1.23      crook    9134: 
1.78      anton    9135: @cindex single-assignment style for locals
                   9136: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9137: every value-flavoured local has only a single assignment and many
                   9138: advantages of functional languages apply to Forth. I.e., programs are
                   9139: easier to analyse, to optimize and to read: It is clear from the
                   9140: definition what the local stands for, it does not turn into something
                   9141: different later.
1.23      crook    9142: 
1.78      anton    9143: E.g., a definition using @code{TO} might look like this:
                   9144: @example
                   9145: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9146:  u1 u2 min 0
                   9147:  ?do
                   9148:    addr1 c@@ addr2 c@@ -
                   9149:    ?dup-if
                   9150:      unloop exit
                   9151:    then
                   9152:    addr1 char+ TO addr1
                   9153:    addr2 char+ TO addr2
                   9154:  loop
                   9155:  u1 u2 - ;
1.26      crook    9156: @end example
1.78      anton    9157: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9158: every loop iteration. @code{strcmp} is a typical example of the
                   9159: readability problems of using @code{TO}. When you start reading
                   9160: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9161: string. Only near the end of the loop you realize that it is something
                   9162: else.
1.23      crook    9163: 
1.78      anton    9164: This can be avoided by defining two locals at the start of the loop that
                   9165: are initialized with the right value for the current iteration.
                   9166: @example
                   9167: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9168:  addr1 addr2
                   9169:  u1 u2 min 0 
                   9170:  ?do @{ s1 s2 @}
                   9171:    s1 c@@ s2 c@@ -
                   9172:    ?dup-if
                   9173:      unloop exit
                   9174:    then
                   9175:    s1 char+ s2 char+
                   9176:  loop
                   9177:  2drop
                   9178:  u1 u2 - ;
                   9179: @end example
                   9180: Here it is clear from the start that @code{s1} has a different value
                   9181: in every loop iteration.
1.23      crook    9182: 
1.78      anton    9183: @node Locals implementation,  , Locals programming style, Gforth locals
                   9184: @subsubsection Locals implementation
                   9185: @cindex locals implementation
                   9186: @cindex implementation of locals
1.23      crook    9187: 
1.78      anton    9188: @cindex locals stack
                   9189: Gforth uses an extra locals stack. The most compelling reason for
                   9190: this is that the return stack is not float-aligned; using an extra stack
                   9191: also eliminates the problems and restrictions of using the return stack
                   9192: as locals stack. Like the other stacks, the locals stack grows toward
                   9193: lower addresses. A few primitives allow an efficient implementation:
                   9194: 
                   9195: 
                   9196: doc-@local#
                   9197: doc-f@local#
                   9198: doc-laddr#
                   9199: doc-lp+!#
                   9200: doc-lp!
                   9201: doc->l
                   9202: doc-f>l
                   9203: 
                   9204: 
                   9205: In addition to these primitives, some specializations of these
                   9206: primitives for commonly occurring inline arguments are provided for
                   9207: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9208: @code{@@local#} for the inline argument 0. The following compiling words
                   9209: compile the right specialized version, or the general version, as
                   9210: appropriate:
1.23      crook    9211: 
1.5       anton    9212: 
1.107     dvdkhlng 9213: @c doc-compile-@local
                   9214: @c doc-compile-f@local
1.78      anton    9215: doc-compile-lp+!
1.5       anton    9216: 
                   9217: 
1.78      anton    9218: Combinations of conditional branches and @code{lp+!#} like
                   9219: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9220: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9221: 
1.78      anton    9222: A special area in the dictionary space is reserved for keeping the
                   9223: local variable names. @code{@{} switches the dictionary pointer to this
                   9224: area and @code{@}} switches it back and generates the locals
                   9225: initializing code. @code{W:} etc.@ are normal defining words. This
                   9226: special area is cleared at the start of every colon definition.
1.5       anton    9227: 
1.78      anton    9228: @cindex word list for defining locals
                   9229: A special feature of Gforth's dictionary is used to implement the
                   9230: definition of locals without type specifiers: every word list (aka
                   9231: vocabulary) has its own methods for searching
                   9232: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9233: with a special search method: When it is searched for a word, it
                   9234: actually creates that word using @code{W:}. @code{@{} changes the search
                   9235: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9236: and then the word list for defining locals without type specifiers.
1.5       anton    9237: 
1.78      anton    9238: The lifetime rules support a stack discipline within a colon
                   9239: definition: The lifetime of a local is either nested with other locals
                   9240: lifetimes or it does not overlap them.
1.23      crook    9241: 
1.78      anton    9242: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9243: pointer manipulation is generated. Between control structure words
                   9244: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9245: is the simplest of the other three control flow words. It has to
                   9246: restore the locals stack depth of the corresponding @code{BEGIN}
                   9247: before branching. The code looks like this:
                   9248: @format
                   9249: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9250: @code{branch} <begin>
                   9251: @end format
1.26      crook    9252: 
1.78      anton    9253: @code{UNTIL} is a little more complicated: If it branches back, it
                   9254: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9255: the locals stack must not be changed. The compiler generates the
                   9256: following code:
                   9257: @format
                   9258: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9259: @end format
                   9260: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9261: 
1.78      anton    9262: @code{THEN} can produce somewhat inefficient code:
                   9263: @format
                   9264: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9265: <orig target>:
                   9266: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9267: @end format
                   9268: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9269: level at the @i{orig} point to the level after the @code{THEN}. The
                   9270: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9271: level to the level at the orig point, so the complete effect is an
                   9272: adjustment from the current level to the right level after the
                   9273: @code{THEN}.
1.26      crook    9274: 
1.78      anton    9275: @cindex locals information on the control-flow stack
                   9276: @cindex control-flow stack items, locals information
                   9277: In a conventional Forth implementation a dest control-flow stack entry
                   9278: is just the target address and an orig entry is just the address to be
                   9279: patched. Our locals implementation adds a word list to every orig or dest
                   9280: item. It is the list of locals visible (or assumed visible) at the point
                   9281: described by the entry. Our implementation also adds a tag to identify
                   9282: the kind of entry, in particular to differentiate between live and dead
                   9283: (reachable and unreachable) orig entries.
1.26      crook    9284: 
1.78      anton    9285: A few unusual operations have to be performed on locals word lists:
1.44      crook    9286: 
1.5       anton    9287: 
1.78      anton    9288: doc-common-list
                   9289: doc-sub-list?
                   9290: doc-list-size
1.52      anton    9291: 
                   9292: 
1.78      anton    9293: Several features of our locals word list implementation make these
                   9294: operations easy to implement: The locals word lists are organised as
                   9295: linked lists; the tails of these lists are shared, if the lists
                   9296: contain some of the same locals; and the address of a name is greater
                   9297: than the address of the names behind it in the list.
1.5       anton    9298: 
1.78      anton    9299: Another important implementation detail is the variable
                   9300: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9301: determine if they can be reached directly or only through the branch
                   9302: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9303: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9304: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9305: 
1.78      anton    9306: Counted loops are similar to other loops in most respects, but
                   9307: @code{LEAVE} requires special attention: It performs basically the same
                   9308: service as @code{AHEAD}, but it does not create a control-flow stack
                   9309: entry. Therefore the information has to be stored elsewhere;
                   9310: traditionally, the information was stored in the target fields of the
                   9311: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9312: linked list. Unfortunately, this clever trick does not provide enough
                   9313: space for storing our extended control flow information. Therefore, we
                   9314: introduce another stack, the leave stack. It contains the control-flow
                   9315: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    9316: 
1.78      anton    9317: Local names are kept until the end of the colon definition, even if
                   9318: they are no longer visible in any control-flow path. In a few cases
                   9319: this may lead to increased space needs for the locals name area, but
                   9320: usually less than reclaiming this space would cost in code size.
1.5       anton    9321: 
1.44      crook    9322: 
1.78      anton    9323: @node ANS Forth locals,  , Gforth locals, Locals
                   9324: @subsection ANS Forth locals
                   9325: @cindex locals, ANS Forth style
1.5       anton    9326: 
1.78      anton    9327: The ANS Forth locals wordset does not define a syntax for locals, but
                   9328: words that make it possible to define various syntaxes. One of the
                   9329: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9330: wordset, i.e.:
1.29      crook    9331: 
                   9332: @example
1.78      anton    9333: @{ local1 local2 ... -- comment @}
                   9334: @end example
                   9335: @noindent
                   9336: or
                   9337: @example
                   9338: @{ local1 local2 ... @}
1.29      crook    9339: @end example
                   9340: 
1.78      anton    9341: The order of the locals corresponds to the order in a stack comment. The
                   9342: restrictions are:
1.5       anton    9343: 
1.78      anton    9344: @itemize @bullet
                   9345: @item
                   9346: Locals can only be cell-sized values (no type specifiers are allowed).
                   9347: @item
                   9348: Locals can be defined only outside control structures.
                   9349: @item
                   9350: Locals can interfere with explicit usage of the return stack. For the
                   9351: exact (and long) rules, see the standard. If you don't use return stack
                   9352: accessing words in a definition using locals, you will be all right. The
                   9353: purpose of this rule is to make locals implementation on the return
                   9354: stack easier.
                   9355: @item
                   9356: The whole definition must be in one line.
                   9357: @end itemize
1.5       anton    9358: 
1.78      anton    9359: Locals defined in ANS Forth behave like @code{VALUE}s
                   9360: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   9361: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    9362: 
1.78      anton    9363: Since the syntax above is supported by Gforth directly, you need not do
                   9364: anything to use it. If you want to port a program using this syntax to
                   9365: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9366: syntax on the other system.
1.5       anton    9367: 
1.78      anton    9368: Note that a syntax shown in the standard, section A.13 looks
                   9369: similar, but is quite different in having the order of locals
                   9370: reversed. Beware!
1.5       anton    9371: 
1.78      anton    9372: The ANS Forth locals wordset itself consists of one word:
1.5       anton    9373: 
1.78      anton    9374: doc-(local)
1.5       anton    9375: 
1.78      anton    9376: The ANS Forth locals extension wordset defines a syntax using
                   9377: @code{locals|}, but it is so awful that we strongly recommend not to use
                   9378: it. We have implemented this syntax to make porting to Gforth easy, but
                   9379: do not document it here. The problem with this syntax is that the locals
                   9380: are defined in an order reversed with respect to the standard stack
                   9381: comment notation, making programs harder to read, and easier to misread
                   9382: and miswrite. The only merit of this syntax is that it is easy to
                   9383: implement using the ANS Forth locals wordset.
1.53      anton    9384: 
                   9385: 
1.78      anton    9386: @c ----------------------------------------------------------
                   9387: @node Structures, Object-oriented Forth, Locals, Words
                   9388: @section  Structures
                   9389: @cindex structures
                   9390: @cindex records
1.53      anton    9391: 
1.78      anton    9392: This section presents the structure package that comes with Gforth. A
                   9393: version of the package implemented in ANS Forth is available in
                   9394: @file{compat/struct.fs}. This package was inspired by a posting on
                   9395: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9396: possibly John Hayes). A version of this section has been published in
                   9397: M. Anton Ertl,
                   9398: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   9399: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   9400: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    9401: 
1.78      anton    9402: @menu
                   9403: * Why explicit structure support?::  
                   9404: * Structure Usage::             
                   9405: * Structure Naming Convention::  
                   9406: * Structure Implementation::    
                   9407: * Structure Glossary::          
                   9408: @end menu
1.55      anton    9409: 
1.78      anton    9410: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9411: @subsection Why explicit structure support?
1.53      anton    9412: 
1.78      anton    9413: @cindex address arithmetic for structures
                   9414: @cindex structures using address arithmetic
                   9415: If we want to use a structure containing several fields, we could simply
                   9416: reserve memory for it, and access the fields using address arithmetic
                   9417: (@pxref{Address arithmetic}). As an example, consider a structure with
                   9418: the following fields
1.57      anton    9419: 
1.78      anton    9420: @table @code
                   9421: @item a
                   9422: is a float
                   9423: @item b
                   9424: is a cell
                   9425: @item c
                   9426: is a float
                   9427: @end table
1.57      anton    9428: 
1.78      anton    9429: Given the (float-aligned) base address of the structure we get the
                   9430: address of the field
1.52      anton    9431: 
1.78      anton    9432: @table @code
                   9433: @item a
                   9434: without doing anything further.
                   9435: @item b
                   9436: with @code{float+}
                   9437: @item c
                   9438: with @code{float+ cell+ faligned}
                   9439: @end table
1.52      anton    9440: 
1.78      anton    9441: It is easy to see that this can become quite tiring. 
1.52      anton    9442: 
1.78      anton    9443: Moreover, it is not very readable, because seeing a
                   9444: @code{cell+} tells us neither which kind of structure is
                   9445: accessed nor what field is accessed; we have to somehow infer the kind
                   9446: of structure, and then look up in the documentation, which field of
                   9447: that structure corresponds to that offset.
1.53      anton    9448: 
1.78      anton    9449: Finally, this kind of address arithmetic also causes maintenance
                   9450: troubles: If you add or delete a field somewhere in the middle of the
                   9451: structure, you have to find and change all computations for the fields
                   9452: afterwards.
1.52      anton    9453: 
1.78      anton    9454: So, instead of using @code{cell+} and friends directly, how
                   9455: about storing the offsets in constants:
1.52      anton    9456: 
1.78      anton    9457: @example
                   9458: 0 constant a-offset
                   9459: 0 float+ constant b-offset
                   9460: 0 float+ cell+ faligned c-offset
                   9461: @end example
1.64      pazsan   9462: 
1.78      anton    9463: Now we can get the address of field @code{x} with @code{x-offset
                   9464: +}. This is much better in all respects. Of course, you still
                   9465: have to change all later offset definitions if you add a field. You can
                   9466: fix this by declaring the offsets in the following way:
1.57      anton    9467: 
1.78      anton    9468: @example
                   9469: 0 constant a-offset
                   9470: a-offset float+ constant b-offset
                   9471: b-offset cell+ faligned constant c-offset
                   9472: @end example
1.57      anton    9473: 
1.78      anton    9474: Since we always use the offsets with @code{+}, we could use a defining
                   9475: word @code{cfield} that includes the @code{+} in the action of the
                   9476: defined word:
1.64      pazsan   9477: 
1.78      anton    9478: @example
                   9479: : cfield ( n "name" -- )
                   9480:     create ,
                   9481: does> ( name execution: addr1 -- addr2 )
                   9482:     @@ + ;
1.64      pazsan   9483: 
1.78      anton    9484: 0 cfield a
                   9485: 0 a float+ cfield b
                   9486: 0 b cell+ faligned cfield c
                   9487: @end example
1.64      pazsan   9488: 
1.78      anton    9489: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   9490: 
1.78      anton    9491: The structure field words now can be used quite nicely. However,
                   9492: their definition is still a bit cumbersome: We have to repeat the
                   9493: name, the information about size and alignment is distributed before
                   9494: and after the field definitions etc.  The structure package presented
                   9495: here addresses these problems.
1.64      pazsan   9496: 
1.78      anton    9497: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9498: @subsection Structure Usage
                   9499: @cindex structure usage
1.57      anton    9500: 
1.78      anton    9501: @cindex @code{field} usage
                   9502: @cindex @code{struct} usage
                   9503: @cindex @code{end-struct} usage
                   9504: You can define a structure for a (data-less) linked list with:
1.57      anton    9505: @example
1.78      anton    9506: struct
                   9507:     cell% field list-next
                   9508: end-struct list%
1.57      anton    9509: @end example
                   9510: 
1.78      anton    9511: With the address of the list node on the stack, you can compute the
                   9512: address of the field that contains the address of the next node with
                   9513: @code{list-next}. E.g., you can determine the length of a list
                   9514: with:
1.57      anton    9515: 
                   9516: @example
1.78      anton    9517: : list-length ( list -- n )
                   9518: \ "list" is a pointer to the first element of a linked list
                   9519: \ "n" is the length of the list
                   9520:     0 BEGIN ( list1 n1 )
                   9521:         over
                   9522:     WHILE ( list1 n1 )
                   9523:         1+ swap list-next @@ swap
                   9524:     REPEAT
                   9525:     nip ;
1.57      anton    9526: @end example
                   9527: 
1.78      anton    9528: You can reserve memory for a list node in the dictionary with
                   9529: @code{list% %allot}, which leaves the address of the list node on the
                   9530: stack. For the equivalent allocation on the heap you can use @code{list%
                   9531: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9532: use @code{list% %allocate}). You can get the the size of a list
                   9533: node with @code{list% %size} and its alignment with @code{list%
                   9534: %alignment}.
                   9535: 
                   9536: Note that in ANS Forth the body of a @code{create}d word is
                   9537: @code{aligned} but not necessarily @code{faligned};
                   9538: therefore, if you do a:
1.57      anton    9539: 
                   9540: @example
1.78      anton    9541: create @emph{name} foo% %allot drop
1.57      anton    9542: @end example
                   9543: 
1.78      anton    9544: @noindent
                   9545: then the memory alloted for @code{foo%} is guaranteed to start at the
                   9546: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   9547: cell and double fields.  Therefore, if your structure contains floats,
                   9548: better use
1.57      anton    9549: 
                   9550: @example
1.78      anton    9551: foo% %allot constant @emph{name}
1.57      anton    9552: @end example
                   9553: 
1.78      anton    9554: @cindex structures containing structures
                   9555: You can include a structure @code{foo%} as a field of
                   9556: another structure, like this:
1.65      anton    9557: @example
1.78      anton    9558: struct
                   9559: ...
                   9560:     foo% field ...
                   9561: ...
                   9562: end-struct ...
1.65      anton    9563: @end example
1.52      anton    9564: 
1.78      anton    9565: @cindex structure extension
                   9566: @cindex extended records
                   9567: Instead of starting with an empty structure, you can extend an
                   9568: existing structure. E.g., a plain linked list without data, as defined
                   9569: above, is hardly useful; You can extend it to a linked list of integers,
                   9570: like this:@footnote{This feature is also known as @emph{extended
                   9571: records}. It is the main innovation in the Oberon language; in other
                   9572: words, adding this feature to Modula-2 led Wirth to create a new
                   9573: language, write a new compiler etc.  Adding this feature to Forth just
                   9574: required a few lines of code.}
1.52      anton    9575: 
1.78      anton    9576: @example
                   9577: list%
                   9578:     cell% field intlist-int
                   9579: end-struct intlist%
                   9580: @end example
1.55      anton    9581: 
1.78      anton    9582: @code{intlist%} is a structure with two fields:
                   9583: @code{list-next} and @code{intlist-int}.
1.55      anton    9584: 
1.78      anton    9585: @cindex structures containing arrays
                   9586: You can specify an array type containing @emph{n} elements of
                   9587: type @code{foo%} like this:
1.55      anton    9588: 
                   9589: @example
1.78      anton    9590: foo% @emph{n} *
1.56      anton    9591: @end example
1.55      anton    9592: 
1.78      anton    9593: You can use this array type in any place where you can use a normal
                   9594: type, e.g., when defining a @code{field}, or with
                   9595: @code{%allot}.
                   9596: 
                   9597: @cindex first field optimization
                   9598: The first field is at the base address of a structure and the word for
                   9599: this field (e.g., @code{list-next}) actually does not change the address
                   9600: on the stack. You may be tempted to leave it away in the interest of
                   9601: run-time and space efficiency. This is not necessary, because the
                   9602: structure package optimizes this case: If you compile a first-field
                   9603: words, no code is generated. So, in the interest of readability and
                   9604: maintainability you should include the word for the field when accessing
                   9605: the field.
1.52      anton    9606: 
                   9607: 
1.78      anton    9608: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   9609: @subsection Structure Naming Convention
                   9610: @cindex structure naming convention
1.52      anton    9611: 
1.78      anton    9612: The field names that come to (my) mind are often quite generic, and,
                   9613: if used, would cause frequent name clashes. E.g., many structures
                   9614: probably contain a @code{counter} field. The structure names
                   9615: that come to (my) mind are often also the logical choice for the names
                   9616: of words that create such a structure.
1.52      anton    9617: 
1.78      anton    9618: Therefore, I have adopted the following naming conventions: 
1.52      anton    9619: 
1.78      anton    9620: @itemize @bullet
                   9621: @cindex field naming convention
                   9622: @item
                   9623: The names of fields are of the form
                   9624: @code{@emph{struct}-@emph{field}}, where
                   9625: @code{@emph{struct}} is the basic name of the structure, and
                   9626: @code{@emph{field}} is the basic name of the field. You can
                   9627: think of field words as converting the (address of the)
                   9628: structure into the (address of the) field.
1.52      anton    9629: 
1.78      anton    9630: @cindex structure naming convention
                   9631: @item
                   9632: The names of structures are of the form
                   9633: @code{@emph{struct}%}, where
                   9634: @code{@emph{struct}} is the basic name of the structure.
                   9635: @end itemize
1.52      anton    9636: 
1.78      anton    9637: This naming convention does not work that well for fields of extended
                   9638: structures; e.g., the integer list structure has a field
                   9639: @code{intlist-int}, but has @code{list-next}, not
                   9640: @code{intlist-next}.
1.53      anton    9641: 
1.78      anton    9642: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   9643: @subsection Structure Implementation
                   9644: @cindex structure implementation
                   9645: @cindex implementation of structures
1.52      anton    9646: 
1.78      anton    9647: The central idea in the implementation is to pass the data about the
                   9648: structure being built on the stack, not in some global
                   9649: variable. Everything else falls into place naturally once this design
                   9650: decision is made.
1.53      anton    9651: 
1.78      anton    9652: The type description on the stack is of the form @emph{align
                   9653: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   9654: very simple.
1.53      anton    9655: 
1.78      anton    9656: @code{field} is a defining word that uses @code{Create}
                   9657: and @code{DOES>}. The body of the field contains the offset
                   9658: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    9659: 
                   9660: @example
1.78      anton    9661: @@ +
1.53      anton    9662: @end example
                   9663: 
1.78      anton    9664: @noindent
                   9665: i.e., add the offset to the address, giving the stack effect
                   9666: @i{addr1 -- addr2} for a field.
                   9667: 
                   9668: @cindex first field optimization, implementation
                   9669: This simple structure is slightly complicated by the optimization
                   9670: for fields with offset 0, which requires a different
                   9671: @code{DOES>}-part (because we cannot rely on there being
                   9672: something on the stack if such a field is invoked during
                   9673: compilation). Therefore, we put the different @code{DOES>}-parts
                   9674: in separate words, and decide which one to invoke based on the
                   9675: offset. For a zero offset, the field is basically a noop; it is
                   9676: immediate, and therefore no code is generated when it is compiled.
1.53      anton    9677: 
1.78      anton    9678: @node Structure Glossary,  , Structure Implementation, Structures
                   9679: @subsection Structure Glossary
                   9680: @cindex structure glossary
1.53      anton    9681: 
1.5       anton    9682: 
1.78      anton    9683: doc-%align
                   9684: doc-%alignment
                   9685: doc-%alloc
                   9686: doc-%allocate
                   9687: doc-%allot
                   9688: doc-cell%
                   9689: doc-char%
                   9690: doc-dfloat%
                   9691: doc-double%
                   9692: doc-end-struct
                   9693: doc-field
                   9694: doc-float%
                   9695: doc-naligned
                   9696: doc-sfloat%
                   9697: doc-%size
                   9698: doc-struct
1.54      anton    9699: 
                   9700: 
1.26      crook    9701: @c -------------------------------------------------------------
1.78      anton    9702: @node Object-oriented Forth, Programming Tools, Structures, Words
                   9703: @section Object-oriented Forth
                   9704: 
                   9705: Gforth comes with three packages for object-oriented programming:
                   9706: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   9707: is preloaded, so you have to @code{include} them before use. The most
                   9708: important differences between these packages (and others) are discussed
                   9709: in @ref{Comparison with other object models}. All packages are written
                   9710: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    9711: 
1.78      anton    9712: @menu
                   9713: * Why object-oriented programming?::  
                   9714: * Object-Oriented Terminology::  
                   9715: * Objects::                     
                   9716: * OOF::                         
                   9717: * Mini-OOF::                    
                   9718: * Comparison with other object models::  
                   9719: @end menu
1.5       anton    9720: 
1.78      anton    9721: @c ----------------------------------------------------------------
                   9722: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   9723: @subsection Why object-oriented programming?
                   9724: @cindex object-oriented programming motivation
                   9725: @cindex motivation for object-oriented programming
1.44      crook    9726: 
1.78      anton    9727: Often we have to deal with several data structures (@emph{objects}),
                   9728: that have to be treated similarly in some respects, but differently in
                   9729: others. Graphical objects are the textbook example: circles, triangles,
                   9730: dinosaurs, icons, and others, and we may want to add more during program
                   9731: development. We want to apply some operations to any graphical object,
                   9732: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   9733: has to do something different for every kind of object.
                   9734: @comment TODO add some other operations eg perimeter, area
                   9735: @comment and tie in to concrete examples later..
1.5       anton    9736: 
1.78      anton    9737: We could implement @code{draw} as a big @code{CASE}
                   9738: control structure that executes the appropriate code depending on the
                   9739: kind of object to be drawn. This would be not be very elegant, and,
                   9740: moreover, we would have to change @code{draw} every time we add
                   9741: a new kind of graphical object (say, a spaceship).
1.44      crook    9742: 
1.78      anton    9743: What we would rather do is: When defining spaceships, we would tell
                   9744: the system: ``Here's how you @code{draw} a spaceship; you figure
                   9745: out the rest''.
1.5       anton    9746: 
1.78      anton    9747: This is the problem that all systems solve that (rightfully) call
                   9748: themselves object-oriented; the object-oriented packages presented here
                   9749: solve this problem (and not much else).
                   9750: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    9751: 
1.78      anton    9752: @c ------------------------------------------------------------------------
                   9753: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   9754: @subsection Object-Oriented Terminology
                   9755: @cindex object-oriented terminology
                   9756: @cindex terminology for object-oriented programming
1.5       anton    9757: 
1.78      anton    9758: This section is mainly for reference, so you don't have to understand
                   9759: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   9760: short:
1.44      crook    9761: 
1.78      anton    9762: @table @emph
                   9763: @cindex class
                   9764: @item class
                   9765: a data structure definition with some extras.
1.5       anton    9766: 
1.78      anton    9767: @cindex object
                   9768: @item object
                   9769: an instance of the data structure described by the class definition.
1.5       anton    9770: 
1.78      anton    9771: @cindex instance variables
                   9772: @item instance variables
                   9773: fields of the data structure.
1.5       anton    9774: 
1.78      anton    9775: @cindex selector
                   9776: @cindex method selector
                   9777: @cindex virtual function
                   9778: @item selector
                   9779: (or @emph{method selector}) a word (e.g.,
                   9780: @code{draw}) that performs an operation on a variety of data
                   9781: structures (classes). A selector describes @emph{what} operation to
                   9782: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    9783: 
1.78      anton    9784: @cindex method
                   9785: @item method
                   9786: the concrete definition that performs the operation
                   9787: described by the selector for a specific class. A method specifies
                   9788: @emph{how} the operation is performed for a specific class.
1.5       anton    9789: 
1.78      anton    9790: @cindex selector invocation
                   9791: @cindex message send
                   9792: @cindex invoking a selector
                   9793: @item selector invocation
                   9794: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   9795: is used for determining which method is used. In Smalltalk terminology:
                   9796: a message (consisting of the selector and the other arguments) is sent
                   9797: to the object.
1.5       anton    9798: 
1.78      anton    9799: @cindex receiving object
                   9800: @item receiving object
                   9801: the object used for determining the method executed by a selector
                   9802: invocation. In the @file{objects.fs} model, it is the object that is on
                   9803: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   9804: the Smalltalk @emph{message} terminology.)
1.5       anton    9805: 
1.78      anton    9806: @cindex child class
                   9807: @cindex parent class
                   9808: @cindex inheritance
                   9809: @item child class
                   9810: a class that has (@emph{inherits}) all properties (instance variables,
                   9811: selectors, methods) from a @emph{parent class}. In Smalltalk
                   9812: terminology: The subclass inherits from the superclass. In C++
                   9813: terminology: The derived class inherits from the base class.
1.5       anton    9814: 
1.78      anton    9815: @end table
1.5       anton    9816: 
1.78      anton    9817: @c If you wonder about the message sending terminology, it comes from
                   9818: @c a time when each object had it's own task and objects communicated via
                   9819: @c message passing; eventually the Smalltalk developers realized that
                   9820: @c they can do most things through simple (indirect) calls. They kept the
                   9821: @c terminology.
1.5       anton    9822: 
1.78      anton    9823: @c --------------------------------------------------------------
                   9824: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   9825: @subsection The @file{objects.fs} model
                   9826: @cindex objects
                   9827: @cindex object-oriented programming
1.26      crook    9828: 
1.78      anton    9829: @cindex @file{objects.fs}
                   9830: @cindex @file{oof.fs}
1.26      crook    9831: 
1.78      anton    9832: This section describes the @file{objects.fs} package. This material also
                   9833: has been published in M. Anton Ertl,
                   9834: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   9835: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   9836: 37--43.
                   9837: @c McKewan's and Zsoter's packages
1.26      crook    9838: 
1.78      anton    9839: This section assumes that you have read @ref{Structures}.
1.5       anton    9840: 
1.78      anton    9841: The techniques on which this model is based have been used to implement
                   9842: the parser generator, Gray, and have also been used in Gforth for
                   9843: implementing the various flavours of word lists (hashed or not,
                   9844: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    9845: 
                   9846: 
1.26      crook    9847: @menu
1.78      anton    9848: * Properties of the Objects model::  
                   9849: * Basic Objects Usage::         
                   9850: * The Objects base class::      
                   9851: * Creating objects::            
                   9852: * Object-Oriented Programming Style::  
                   9853: * Class Binding::               
                   9854: * Method conveniences::         
                   9855: * Classes and Scoping::         
                   9856: * Dividing classes::            
                   9857: * Object Interfaces::           
                   9858: * Objects Implementation::      
                   9859: * Objects Glossary::            
1.26      crook    9860: @end menu
1.5       anton    9861: 
1.78      anton    9862: Marcel Hendrix provided helpful comments on this section.
1.5       anton    9863: 
1.78      anton    9864: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   9865: @subsubsection Properties of the @file{objects.fs} model
                   9866: @cindex @file{objects.fs} properties
1.5       anton    9867: 
1.78      anton    9868: @itemize @bullet
                   9869: @item
                   9870: It is straightforward to pass objects on the stack. Passing
                   9871: selectors on the stack is a little less convenient, but possible.
1.44      crook    9872: 
1.78      anton    9873: @item
                   9874: Objects are just data structures in memory, and are referenced by their
                   9875: address. You can create words for objects with normal defining words
                   9876: like @code{constant}. Likewise, there is no difference between instance
                   9877: variables that contain objects and those that contain other data.
1.5       anton    9878: 
1.78      anton    9879: @item
                   9880: Late binding is efficient and easy to use.
1.44      crook    9881: 
1.78      anton    9882: @item
                   9883: It avoids parsing, and thus avoids problems with state-smartness
                   9884: and reduced extensibility; for convenience there are a few parsing
                   9885: words, but they have non-parsing counterparts. There are also a few
                   9886: defining words that parse. This is hard to avoid, because all standard
                   9887: defining words parse (except @code{:noname}); however, such
                   9888: words are not as bad as many other parsing words, because they are not
                   9889: state-smart.
1.5       anton    9890: 
1.78      anton    9891: @item
                   9892: It does not try to incorporate everything. It does a few things and does
                   9893: them well (IMO). In particular, this model was not designed to support
                   9894: information hiding (although it has features that may help); you can use
                   9895: a separate package for achieving this.
1.5       anton    9896: 
1.78      anton    9897: @item
                   9898: It is layered; you don't have to learn and use all features to use this
                   9899: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   9900: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   9901: are optional and independent of each other.
1.5       anton    9902: 
1.78      anton    9903: @item
                   9904: An implementation in ANS Forth is available.
1.5       anton    9905: 
1.78      anton    9906: @end itemize
1.5       anton    9907: 
1.44      crook    9908: 
1.78      anton    9909: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   9910: @subsubsection Basic @file{objects.fs} Usage
                   9911: @cindex basic objects usage
                   9912: @cindex objects, basic usage
1.5       anton    9913: 
1.78      anton    9914: You can define a class for graphical objects like this:
1.44      crook    9915: 
1.78      anton    9916: @cindex @code{class} usage
                   9917: @cindex @code{end-class} usage
                   9918: @cindex @code{selector} usage
1.5       anton    9919: @example
1.78      anton    9920: object class \ "object" is the parent class
                   9921:   selector draw ( x y graphical -- )
                   9922: end-class graphical
                   9923: @end example
                   9924: 
                   9925: This code defines a class @code{graphical} with an
                   9926: operation @code{draw}.  We can perform the operation
                   9927: @code{draw} on any @code{graphical} object, e.g.:
                   9928: 
                   9929: @example
                   9930: 100 100 t-rex draw
1.26      crook    9931: @end example
1.5       anton    9932: 
1.78      anton    9933: @noindent
                   9934: where @code{t-rex} is a word (say, a constant) that produces a
                   9935: graphical object.
                   9936: 
                   9937: @comment TODO add a 2nd operation eg perimeter.. and use for
                   9938: @comment a concrete example
1.5       anton    9939: 
1.78      anton    9940: @cindex abstract class
                   9941: How do we create a graphical object? With the present definitions,
                   9942: we cannot create a useful graphical object. The class
                   9943: @code{graphical} describes graphical objects in general, but not
                   9944: any concrete graphical object type (C++ users would call it an
                   9945: @emph{abstract class}); e.g., there is no method for the selector
                   9946: @code{draw} in the class @code{graphical}.
1.5       anton    9947: 
1.78      anton    9948: For concrete graphical objects, we define child classes of the
                   9949: class @code{graphical}, e.g.:
1.5       anton    9950: 
1.78      anton    9951: @cindex @code{overrides} usage
                   9952: @cindex @code{field} usage in class definition
1.26      crook    9953: @example
1.78      anton    9954: graphical class \ "graphical" is the parent class
                   9955:   cell% field circle-radius
1.5       anton    9956: 
1.78      anton    9957: :noname ( x y circle -- )
                   9958:   circle-radius @@ draw-circle ;
                   9959: overrides draw
1.5       anton    9960: 
1.78      anton    9961: :noname ( n-radius circle -- )
                   9962:   circle-radius ! ;
                   9963: overrides construct
1.5       anton    9964: 
1.78      anton    9965: end-class circle
                   9966: @end example
1.44      crook    9967: 
1.78      anton    9968: Here we define a class @code{circle} as a child of @code{graphical},
                   9969: with field @code{circle-radius} (which behaves just like a field
                   9970: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   9971: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   9972: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    9973: 
1.78      anton    9974: Now we can create a circle on the heap (i.e.,
                   9975: @code{allocate}d memory) with:
1.44      crook    9976: 
1.78      anton    9977: @cindex @code{heap-new} usage
1.5       anton    9978: @example
1.78      anton    9979: 50 circle heap-new constant my-circle
1.5       anton    9980: @end example
                   9981: 
1.78      anton    9982: @noindent
                   9983: @code{heap-new} invokes @code{construct}, thus
                   9984: initializing the field @code{circle-radius} with 50. We can draw
                   9985: this new circle at (100,100) with:
1.5       anton    9986: 
                   9987: @example
1.78      anton    9988: 100 100 my-circle draw
1.5       anton    9989: @end example
                   9990: 
1.78      anton    9991: @cindex selector invocation, restrictions
                   9992: @cindex class definition, restrictions
                   9993: Note: You can only invoke a selector if the object on the TOS
                   9994: (the receiving object) belongs to the class where the selector was
                   9995: defined or one of its descendents; e.g., you can invoke
                   9996: @code{draw} only for objects belonging to @code{graphical}
                   9997: or its descendents (e.g., @code{circle}).  Immediately before
                   9998: @code{end-class}, the search order has to be the same as
                   9999: immediately after @code{class}.
                   10000: 
                   10001: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10002: @subsubsection The @file{object.fs} base class
                   10003: @cindex @code{object} class
                   10004: 
                   10005: When you define a class, you have to specify a parent class.  So how do
                   10006: you start defining classes? There is one class available from the start:
                   10007: @code{object}. It is ancestor for all classes and so is the
                   10008: only class that has no parent. It has two selectors: @code{construct}
                   10009: and @code{print}.
                   10010: 
                   10011: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10012: @subsubsection Creating objects
                   10013: @cindex creating objects
                   10014: @cindex object creation
                   10015: @cindex object allocation options
                   10016: 
                   10017: @cindex @code{heap-new} discussion
                   10018: @cindex @code{dict-new} discussion
                   10019: @cindex @code{construct} discussion
                   10020: You can create and initialize an object of a class on the heap with
                   10021: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10022: (allocation with @code{allot}) with @code{dict-new} (
                   10023: ... class -- object ). Both words invoke @code{construct}, which
                   10024: consumes the stack items indicated by "..." above.
                   10025: 
                   10026: @cindex @code{init-object} discussion
                   10027: @cindex @code{class-inst-size} discussion
                   10028: If you want to allocate memory for an object yourself, you can get its
                   10029: alignment and size with @code{class-inst-size 2@@} ( class --
                   10030: align size ). Once you have memory for an object, you can initialize
                   10031: it with @code{init-object} ( ... class object -- );
                   10032: @code{construct} does only a part of the necessary work.
                   10033: 
                   10034: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10035: @subsubsection Object-Oriented Programming Style
                   10036: @cindex object-oriented programming style
                   10037: @cindex programming style, object-oriented
1.5       anton    10038: 
1.78      anton    10039: This section is not exhaustive.
1.5       anton    10040: 
1.78      anton    10041: @cindex stack effects of selectors
                   10042: @cindex selectors and stack effects
                   10043: In general, it is a good idea to ensure that all methods for the
                   10044: same selector have the same stack effect: when you invoke a selector,
                   10045: you often have no idea which method will be invoked, so, unless all
                   10046: methods have the same stack effect, you will not know the stack effect
                   10047: of the selector invocation.
1.5       anton    10048: 
1.78      anton    10049: One exception to this rule is methods for the selector
                   10050: @code{construct}. We know which method is invoked, because we
                   10051: specify the class to be constructed at the same place. Actually, I
                   10052: defined @code{construct} as a selector only to give the users a
                   10053: convenient way to specify initialization. The way it is used, a
                   10054: mechanism different from selector invocation would be more natural
                   10055: (but probably would take more code and more space to explain).
1.5       anton    10056: 
1.78      anton    10057: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10058: @subsubsection Class Binding
                   10059: @cindex class binding
                   10060: @cindex early binding
1.5       anton    10061: 
1.78      anton    10062: @cindex late binding
                   10063: Normal selector invocations determine the method at run-time depending
                   10064: on the class of the receiving object. This run-time selection is called
                   10065: @i{late binding}.
1.5       anton    10066: 
1.78      anton    10067: Sometimes it's preferable to invoke a different method. For example,
                   10068: you might want to use the simple method for @code{print}ing
                   10069: @code{object}s instead of the possibly long-winded @code{print} method
                   10070: of the receiver class. You can achieve this by replacing the invocation
                   10071: of @code{print} with:
1.5       anton    10072: 
1.78      anton    10073: @cindex @code{[bind]} usage
1.5       anton    10074: @example
1.78      anton    10075: [bind] object print
1.5       anton    10076: @end example
                   10077: 
1.78      anton    10078: @noindent
                   10079: in compiled code or:
                   10080: 
                   10081: @cindex @code{bind} usage
1.5       anton    10082: @example
1.78      anton    10083: bind object print
1.5       anton    10084: @end example
                   10085: 
1.78      anton    10086: @cindex class binding, alternative to
                   10087: @noindent
                   10088: in interpreted code. Alternatively, you can define the method with a
                   10089: name (e.g., @code{print-object}), and then invoke it through the
                   10090: name. Class binding is just a (often more convenient) way to achieve
                   10091: the same effect; it avoids name clutter and allows you to invoke
                   10092: methods directly without naming them first.
1.5       anton    10093: 
1.78      anton    10094: @cindex superclass binding
                   10095: @cindex parent class binding
                   10096: A frequent use of class binding is this: When we define a method
                   10097: for a selector, we often want the method to do what the selector does
                   10098: in the parent class, and a little more. There is a special word for
                   10099: this purpose: @code{[parent]}; @code{[parent]
                   10100: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10101: selector}}, where @code{@emph{parent}} is the parent
                   10102: class of the current class. E.g., a method definition might look like:
1.44      crook    10103: 
1.78      anton    10104: @cindex @code{[parent]} usage
                   10105: @example
                   10106: :noname
                   10107:   dup [parent] foo \ do parent's foo on the receiving object
                   10108:   ... \ do some more
                   10109: ; overrides foo
                   10110: @end example
1.6       pazsan   10111: 
1.78      anton    10112: @cindex class binding as optimization
                   10113: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10114: March 1997), Andrew McKewan presents class binding as an optimization
                   10115: technique. I recommend not using it for this purpose unless you are in
                   10116: an emergency. Late binding is pretty fast with this model anyway, so the
                   10117: benefit of using class binding is small; the cost of using class binding
                   10118: where it is not appropriate is reduced maintainability.
1.44      crook    10119: 
1.78      anton    10120: While we are at programming style questions: You should bind
                   10121: selectors only to ancestor classes of the receiving object. E.g., say,
                   10122: you know that the receiving object is of class @code{foo} or its
                   10123: descendents; then you should bind only to @code{foo} and its
                   10124: ancestors.
1.12      anton    10125: 
1.78      anton    10126: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10127: @subsubsection Method conveniences
                   10128: @cindex method conveniences
1.44      crook    10129: 
1.78      anton    10130: In a method you usually access the receiving object pretty often.  If
                   10131: you define the method as a plain colon definition (e.g., with
                   10132: @code{:noname}), you may have to do a lot of stack
                   10133: gymnastics. To avoid this, you can define the method with @code{m:
                   10134: ... ;m}. E.g., you could define the method for
                   10135: @code{draw}ing a @code{circle} with
1.6       pazsan   10136: 
1.78      anton    10137: @cindex @code{this} usage
                   10138: @cindex @code{m:} usage
                   10139: @cindex @code{;m} usage
                   10140: @example
                   10141: m: ( x y circle -- )
                   10142:   ( x y ) this circle-radius @@ draw-circle ;m
                   10143: @end example
1.6       pazsan   10144: 
1.78      anton    10145: @cindex @code{exit} in @code{m: ... ;m}
                   10146: @cindex @code{exitm} discussion
                   10147: @cindex @code{catch} in @code{m: ... ;m}
                   10148: When this method is executed, the receiver object is removed from the
                   10149: stack; you can access it with @code{this} (admittedly, in this
                   10150: example the use of @code{m: ... ;m} offers no advantage). Note
                   10151: that I specify the stack effect for the whole method (i.e. including
                   10152: the receiver object), not just for the code between @code{m:}
                   10153: and @code{;m}. You cannot use @code{exit} in
                   10154: @code{m:...;m}; instead, use
                   10155: @code{exitm}.@footnote{Moreover, for any word that calls
                   10156: @code{catch} and was defined before loading
                   10157: @code{objects.fs}, you have to redefine it like I redefined
                   10158: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10159: 
1.78      anton    10160: @cindex @code{inst-var} usage
                   10161: You will frequently use sequences of the form @code{this
                   10162: @emph{field}} (in the example above: @code{this
                   10163: circle-radius}). If you use the field only in this way, you can
                   10164: define it with @code{inst-var} and eliminate the
                   10165: @code{this} before the field name. E.g., the @code{circle}
                   10166: class above could also be defined with:
1.6       pazsan   10167: 
1.78      anton    10168: @example
                   10169: graphical class
                   10170:   cell% inst-var radius
1.6       pazsan   10171: 
1.78      anton    10172: m: ( x y circle -- )
                   10173:   radius @@ draw-circle ;m
                   10174: overrides draw
1.6       pazsan   10175: 
1.78      anton    10176: m: ( n-radius circle -- )
                   10177:   radius ! ;m
                   10178: overrides construct
1.6       pazsan   10179: 
1.78      anton    10180: end-class circle
                   10181: @end example
1.6       pazsan   10182: 
1.78      anton    10183: @code{radius} can only be used in @code{circle} and its
                   10184: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10185: 
1.78      anton    10186: @cindex @code{inst-value} usage
                   10187: You can also define fields with @code{inst-value}, which is
                   10188: to @code{inst-var} what @code{value} is to
                   10189: @code{variable}.  You can change the value of such a field with
                   10190: @code{[to-inst]}.  E.g., we could also define the class
                   10191: @code{circle} like this:
1.44      crook    10192: 
1.78      anton    10193: @example
                   10194: graphical class
                   10195:   inst-value radius
1.6       pazsan   10196: 
1.78      anton    10197: m: ( x y circle -- )
                   10198:   radius draw-circle ;m
                   10199: overrides draw
1.44      crook    10200: 
1.78      anton    10201: m: ( n-radius circle -- )
                   10202:   [to-inst] radius ;m
                   10203: overrides construct
1.6       pazsan   10204: 
1.78      anton    10205: end-class circle
                   10206: @end example
1.6       pazsan   10207: 
1.78      anton    10208: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10209: 
1.78      anton    10210: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10211: @c feature is the definition of words that occur only in one class and are
                   10212: @c not intended to be overridden, but which still need method context
                   10213: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10214: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10215: 
                   10216: 
1.78      anton    10217: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10218: @subsubsection Classes and Scoping
                   10219: @cindex classes and scoping
                   10220: @cindex scoping and classes
1.6       pazsan   10221: 
1.78      anton    10222: Inheritance is frequent, unlike structure extension. This exacerbates
                   10223: the problem with the field name convention (@pxref{Structure Naming
                   10224: Convention}): One always has to remember in which class the field was
                   10225: originally defined; changing a part of the class structure would require
                   10226: changes for renaming in otherwise unaffected code.
1.6       pazsan   10227: 
1.78      anton    10228: @cindex @code{inst-var} visibility
                   10229: @cindex @code{inst-value} visibility
                   10230: To solve this problem, I added a scoping mechanism (which was not in my
                   10231: original charter): A field defined with @code{inst-var} (or
                   10232: @code{inst-value}) is visible only in the class where it is defined and in
                   10233: the descendent classes of this class.  Using such fields only makes
                   10234: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10235: 
1.78      anton    10236: This scoping mechanism allows us to use the unadorned field name,
                   10237: because name clashes with unrelated words become much less likely.
1.6       pazsan   10238: 
1.78      anton    10239: @cindex @code{protected} discussion
                   10240: @cindex @code{private} discussion
                   10241: Once we have this mechanism, we can also use it for controlling the
                   10242: visibility of other words: All words defined after
                   10243: @code{protected} are visible only in the current class and its
                   10244: descendents. @code{public} restores the compilation
                   10245: (i.e. @code{current}) word list that was in effect before. If you
                   10246: have several @code{protected}s without an intervening
                   10247: @code{public} or @code{set-current}, @code{public}
                   10248: will restore the compilation word list in effect before the first of
                   10249: these @code{protected}s.
1.6       pazsan   10250: 
1.78      anton    10251: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10252: @subsubsection Dividing classes
                   10253: @cindex Dividing classes
                   10254: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10255: 
1.78      anton    10256: You may want to do the definition of methods separate from the
                   10257: definition of the class, its selectors, fields, and instance variables,
                   10258: i.e., separate the implementation from the definition.  You can do this
                   10259: in the following way:
1.6       pazsan   10260: 
1.78      anton    10261: @example
                   10262: graphical class
                   10263:   inst-value radius
                   10264: end-class circle
1.6       pazsan   10265: 
1.78      anton    10266: ... \ do some other stuff
1.6       pazsan   10267: 
1.78      anton    10268: circle methods \ now we are ready
1.44      crook    10269: 
1.78      anton    10270: m: ( x y circle -- )
                   10271:   radius draw-circle ;m
                   10272: overrides draw
1.6       pazsan   10273: 
1.78      anton    10274: m: ( n-radius circle -- )
                   10275:   [to-inst] radius ;m
                   10276: overrides construct
1.44      crook    10277: 
1.78      anton    10278: end-methods
                   10279: @end example
1.7       pazsan   10280: 
1.78      anton    10281: You can use several @code{methods}...@code{end-methods} sections.  The
                   10282: only things you can do to the class in these sections are: defining
                   10283: methods, and overriding the class's selectors.  You must not define new
                   10284: selectors or fields.
1.7       pazsan   10285: 
1.78      anton    10286: Note that you often have to override a selector before using it.  In
                   10287: particular, you usually have to override @code{construct} with a new
                   10288: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10289: must not create a circle before the @code{overrides construct} sequence
                   10290: in the example above.
1.7       pazsan   10291: 
1.78      anton    10292: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   10293: @subsubsection Object Interfaces
                   10294: @cindex object interfaces
                   10295: @cindex interfaces for objects
1.7       pazsan   10296: 
1.78      anton    10297: In this model you can only call selectors defined in the class of the
                   10298: receiving objects or in one of its ancestors. If you call a selector
                   10299: with a receiving object that is not in one of these classes, the
                   10300: result is undefined; if you are lucky, the program crashes
                   10301: immediately.
1.7       pazsan   10302: 
1.78      anton    10303: @cindex selectors common to hardly-related classes
                   10304: Now consider the case when you want to have a selector (or several)
                   10305: available in two classes: You would have to add the selector to a
                   10306: common ancestor class, in the worst case to @code{object}. You
                   10307: may not want to do this, e.g., because someone else is responsible for
                   10308: this ancestor class.
1.7       pazsan   10309: 
1.78      anton    10310: The solution for this problem is interfaces. An interface is a
                   10311: collection of selectors. If a class implements an interface, the
                   10312: selectors become available to the class and its descendents. A class
                   10313: can implement an unlimited number of interfaces. For the problem
                   10314: discussed above, we would define an interface for the selector(s), and
                   10315: both classes would implement the interface.
1.7       pazsan   10316: 
1.78      anton    10317: As an example, consider an interface @code{storage} for
                   10318: writing objects to disk and getting them back, and a class
                   10319: @code{foo} that implements it. The code would look like this:
1.7       pazsan   10320: 
1.78      anton    10321: @cindex @code{interface} usage
                   10322: @cindex @code{end-interface} usage
                   10323: @cindex @code{implementation} usage
                   10324: @example
                   10325: interface
                   10326:   selector write ( file object -- )
                   10327:   selector read1 ( file object -- )
                   10328: end-interface storage
1.13      pazsan   10329: 
1.78      anton    10330: bar class
                   10331:   storage implementation
1.13      pazsan   10332: 
1.78      anton    10333: ... overrides write
                   10334: ... overrides read1
                   10335: ...
                   10336: end-class foo
                   10337: @end example
1.13      pazsan   10338: 
1.78      anton    10339: @noindent
                   10340: (I would add a word @code{read} @i{( file -- object )} that uses
                   10341: @code{read1} internally, but that's beyond the point illustrated
                   10342: here.)
1.13      pazsan   10343: 
1.78      anton    10344: Note that you cannot use @code{protected} in an interface; and
                   10345: of course you cannot define fields.
1.13      pazsan   10346: 
1.78      anton    10347: In the Neon model, all selectors are available for all classes;
                   10348: therefore it does not need interfaces. The price you pay in this model
                   10349: is slower late binding, and therefore, added complexity to avoid late
                   10350: binding.
1.13      pazsan   10351: 
1.78      anton    10352: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10353: @subsubsection @file{objects.fs} Implementation
                   10354: @cindex @file{objects.fs} implementation
1.13      pazsan   10355: 
1.78      anton    10356: @cindex @code{object-map} discussion
                   10357: An object is a piece of memory, like one of the data structures
                   10358: described with @code{struct...end-struct}. It has a field
                   10359: @code{object-map} that points to the method map for the object's
                   10360: class.
1.13      pazsan   10361: 
1.78      anton    10362: @cindex method map
                   10363: @cindex virtual function table
                   10364: The @emph{method map}@footnote{This is Self terminology; in C++
                   10365: terminology: virtual function table.} is an array that contains the
                   10366: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   10367: selector contains an offset into a method map.
1.13      pazsan   10368: 
1.78      anton    10369: @cindex @code{selector} implementation, class
                   10370: @code{selector} is a defining word that uses
                   10371: @code{CREATE} and @code{DOES>}. The body of the
                   10372: selector contains the offset; the @code{DOES>} action for a
                   10373: class selector is, basically:
1.8       pazsan   10374: 
                   10375: @example
1.78      anton    10376: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   10377: @end example
                   10378: 
1.78      anton    10379: Since @code{object-map} is the first field of the object, it
                   10380: does not generate any code. As you can see, calling a selector has a
                   10381: small, constant cost.
1.26      crook    10382: 
1.78      anton    10383: @cindex @code{current-interface} discussion
                   10384: @cindex class implementation and representation
                   10385: A class is basically a @code{struct} combined with a method
                   10386: map. During the class definition the alignment and size of the class
                   10387: are passed on the stack, just as with @code{struct}s, so
                   10388: @code{field} can also be used for defining class
                   10389: fields. However, passing more items on the stack would be
                   10390: inconvenient, so @code{class} builds a data structure in memory,
                   10391: which is accessed through the variable
                   10392: @code{current-interface}. After its definition is complete, the
                   10393: class is represented on the stack by a pointer (e.g., as parameter for
                   10394: a child class definition).
1.26      crook    10395: 
1.78      anton    10396: A new class starts off with the alignment and size of its parent,
                   10397: and a copy of the parent's method map. Defining new fields extends the
                   10398: size and alignment; likewise, defining new selectors extends the
                   10399: method map. @code{overrides} just stores a new @i{xt} in the method
                   10400: map at the offset given by the selector.
1.13      pazsan   10401: 
1.78      anton    10402: @cindex class binding, implementation
                   10403: Class binding just gets the @i{xt} at the offset given by the selector
                   10404: from the class's method map and @code{compile,}s (in the case of
                   10405: @code{[bind]}) it.
1.13      pazsan   10406: 
1.78      anton    10407: @cindex @code{this} implementation
                   10408: @cindex @code{catch} and @code{this}
                   10409: @cindex @code{this} and @code{catch}
                   10410: I implemented @code{this} as a @code{value}. At the
                   10411: start of an @code{m:...;m} method the old @code{this} is
                   10412: stored to the return stack and restored at the end; and the object on
                   10413: the TOS is stored @code{TO this}. This technique has one
                   10414: disadvantage: If the user does not leave the method via
                   10415: @code{;m}, but via @code{throw} or @code{exit},
                   10416: @code{this} is not restored (and @code{exit} may
                   10417: crash). To deal with the @code{throw} problem, I have redefined
                   10418: @code{catch} to save and restore @code{this}; the same
                   10419: should be done with any word that can catch an exception. As for
                   10420: @code{exit}, I simply forbid it (as a replacement, there is
                   10421: @code{exitm}).
1.13      pazsan   10422: 
1.78      anton    10423: @cindex @code{inst-var} implementation
                   10424: @code{inst-var} is just the same as @code{field}, with
                   10425: a different @code{DOES>} action:
1.13      pazsan   10426: @example
1.78      anton    10427: @@ this +
1.8       pazsan   10428: @end example
1.78      anton    10429: Similar for @code{inst-value}.
1.8       pazsan   10430: 
1.78      anton    10431: @cindex class scoping implementation
                   10432: Each class also has a word list that contains the words defined with
                   10433: @code{inst-var} and @code{inst-value}, and its protected
                   10434: words. It also has a pointer to its parent. @code{class} pushes
                   10435: the word lists of the class and all its ancestors onto the search order stack,
                   10436: and @code{end-class} drops them.
1.20      pazsan   10437: 
1.78      anton    10438: @cindex interface implementation
                   10439: An interface is like a class without fields, parent and protected
                   10440: words; i.e., it just has a method map. If a class implements an
                   10441: interface, its method map contains a pointer to the method map of the
                   10442: interface. The positive offsets in the map are reserved for class
                   10443: methods, therefore interface map pointers have negative
                   10444: offsets. Interfaces have offsets that are unique throughout the
                   10445: system, unlike class selectors, whose offsets are only unique for the
                   10446: classes where the selector is available (invokable).
1.20      pazsan   10447: 
1.78      anton    10448: This structure means that interface selectors have to perform one
                   10449: indirection more than class selectors to find their method. Their body
                   10450: contains the interface map pointer offset in the class method map, and
                   10451: the method offset in the interface method map. The
                   10452: @code{does>} action for an interface selector is, basically:
1.20      pazsan   10453: 
                   10454: @example
1.78      anton    10455: ( object selector-body )
                   10456: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10457: swap object-map @@ + @@ ( object selector-body map )
                   10458: swap selector-offset @@ + @@ execute
1.20      pazsan   10459: @end example
                   10460: 
1.78      anton    10461: where @code{object-map} and @code{selector-offset} are
                   10462: first fields and generate no code.
1.20      pazsan   10463: 
1.78      anton    10464: As a concrete example, consider the following code:
1.20      pazsan   10465: 
                   10466: @example
1.78      anton    10467: interface
                   10468:   selector if1sel1
                   10469:   selector if1sel2
                   10470: end-interface if1
1.20      pazsan   10471: 
1.78      anton    10472: object class
                   10473:   if1 implementation
                   10474:   selector cl1sel1
                   10475:   cell% inst-var cl1iv1
1.20      pazsan   10476: 
1.78      anton    10477: ' m1 overrides construct
                   10478: ' m2 overrides if1sel1
                   10479: ' m3 overrides if1sel2
                   10480: ' m4 overrides cl1sel2
                   10481: end-class cl1
1.20      pazsan   10482: 
1.78      anton    10483: create obj1 object dict-new drop
                   10484: create obj2 cl1    dict-new drop
                   10485: @end example
1.20      pazsan   10486: 
1.78      anton    10487: The data structure created by this code (including the data structure
                   10488: for @code{object}) is shown in the
                   10489: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   10490: @comment TODO add this diagram..
1.20      pazsan   10491: 
1.78      anton    10492: @node Objects Glossary,  , Objects Implementation, Objects
                   10493: @subsubsection @file{objects.fs} Glossary
                   10494: @cindex @file{objects.fs} Glossary
1.20      pazsan   10495: 
                   10496: 
1.78      anton    10497: doc---objects-bind
                   10498: doc---objects-<bind>
                   10499: doc---objects-bind'
                   10500: doc---objects-[bind]
                   10501: doc---objects-class
                   10502: doc---objects-class->map
                   10503: doc---objects-class-inst-size
                   10504: doc---objects-class-override!
1.79      anton    10505: doc---objects-class-previous
                   10506: doc---objects-class>order
1.78      anton    10507: doc---objects-construct
                   10508: doc---objects-current'
                   10509: doc---objects-[current]
                   10510: doc---objects-current-interface
                   10511: doc---objects-dict-new
                   10512: doc---objects-end-class
                   10513: doc---objects-end-class-noname
                   10514: doc---objects-end-interface
                   10515: doc---objects-end-interface-noname
                   10516: doc---objects-end-methods
                   10517: doc---objects-exitm
                   10518: doc---objects-heap-new
                   10519: doc---objects-implementation
                   10520: doc---objects-init-object
                   10521: doc---objects-inst-value
                   10522: doc---objects-inst-var
                   10523: doc---objects-interface
                   10524: doc---objects-m:
                   10525: doc---objects-:m
                   10526: doc---objects-;m
                   10527: doc---objects-method
                   10528: doc---objects-methods
                   10529: doc---objects-object
                   10530: doc---objects-overrides
                   10531: doc---objects-[parent]
                   10532: doc---objects-print
                   10533: doc---objects-protected
                   10534: doc---objects-public
                   10535: doc---objects-selector
                   10536: doc---objects-this
                   10537: doc---objects-<to-inst>
                   10538: doc---objects-[to-inst]
                   10539: doc---objects-to-this
                   10540: doc---objects-xt-new
1.20      pazsan   10541: 
                   10542: 
1.78      anton    10543: @c -------------------------------------------------------------
                   10544: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10545: @subsection The @file{oof.fs} model
                   10546: @cindex oof
                   10547: @cindex object-oriented programming
1.20      pazsan   10548: 
1.78      anton    10549: @cindex @file{objects.fs}
                   10550: @cindex @file{oof.fs}
1.20      pazsan   10551: 
1.78      anton    10552: This section describes the @file{oof.fs} package.
1.20      pazsan   10553: 
1.78      anton    10554: The package described in this section has been used in bigFORTH since 1991, and
                   10555: used for two large applications: a chromatographic system used to
                   10556: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   10557: 
1.78      anton    10558: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   10559: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   10560: 10(2), 1994.
1.20      pazsan   10561: 
1.78      anton    10562: @menu
                   10563: * Properties of the OOF model::  
                   10564: * Basic OOF Usage::             
                   10565: * The OOF base class::          
                   10566: * Class Declaration::           
                   10567: * Class Implementation::        
                   10568: @end menu
1.20      pazsan   10569: 
1.78      anton    10570: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   10571: @subsubsection Properties of the @file{oof.fs} model
                   10572: @cindex @file{oof.fs} properties
1.20      pazsan   10573: 
1.78      anton    10574: @itemize @bullet
                   10575: @item
                   10576: This model combines object oriented programming with information
                   10577: hiding. It helps you writing large application, where scoping is
                   10578: necessary, because it provides class-oriented scoping.
1.20      pazsan   10579: 
1.78      anton    10580: @item
                   10581: Named objects, object pointers, and object arrays can be created,
                   10582: selector invocation uses the ``object selector'' syntax. Selector invocation
                   10583: to objects and/or selectors on the stack is a bit less convenient, but
                   10584: possible.
1.44      crook    10585: 
1.78      anton    10586: @item
                   10587: Selector invocation and instance variable usage of the active object is
                   10588: straightforward, since both make use of the active object.
1.44      crook    10589: 
1.78      anton    10590: @item
                   10591: Late binding is efficient and easy to use.
1.20      pazsan   10592: 
1.78      anton    10593: @item
                   10594: State-smart objects parse selectors. However, extensibility is provided
                   10595: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   10596: 
1.78      anton    10597: @item
                   10598: An implementation in ANS Forth is available.
1.20      pazsan   10599: 
1.78      anton    10600: @end itemize
1.23      crook    10601: 
                   10602: 
1.78      anton    10603: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   10604: @subsubsection Basic @file{oof.fs} Usage
                   10605: @cindex @file{oof.fs} usage
1.23      crook    10606: 
1.78      anton    10607: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    10608: 
1.78      anton    10609: You can define a class for graphical objects like this:
1.23      crook    10610: 
1.78      anton    10611: @cindex @code{class} usage
                   10612: @cindex @code{class;} usage
                   10613: @cindex @code{method} usage
                   10614: @example
                   10615: object class graphical \ "object" is the parent class
                   10616:   method draw ( x y graphical -- )
                   10617: class;
                   10618: @end example
1.23      crook    10619: 
1.78      anton    10620: This code defines a class @code{graphical} with an
                   10621: operation @code{draw}.  We can perform the operation
                   10622: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    10623: 
1.78      anton    10624: @example
                   10625: 100 100 t-rex draw
                   10626: @end example
1.23      crook    10627: 
1.78      anton    10628: @noindent
                   10629: where @code{t-rex} is an object or object pointer, created with e.g.
                   10630: @code{graphical : t-rex}.
1.23      crook    10631: 
1.78      anton    10632: @cindex abstract class
                   10633: How do we create a graphical object? With the present definitions,
                   10634: we cannot create a useful graphical object. The class
                   10635: @code{graphical} describes graphical objects in general, but not
                   10636: any concrete graphical object type (C++ users would call it an
                   10637: @emph{abstract class}); e.g., there is no method for the selector
                   10638: @code{draw} in the class @code{graphical}.
1.23      crook    10639: 
1.78      anton    10640: For concrete graphical objects, we define child classes of the
                   10641: class @code{graphical}, e.g.:
1.23      crook    10642: 
1.78      anton    10643: @example
                   10644: graphical class circle \ "graphical" is the parent class
                   10645:   cell var circle-radius
                   10646: how:
                   10647:   : draw ( x y -- )
                   10648:     circle-radius @@ draw-circle ;
1.23      crook    10649: 
1.78      anton    10650:   : init ( n-radius -- (
                   10651:     circle-radius ! ;
                   10652: class;
                   10653: @end example
1.1       anton    10654: 
1.78      anton    10655: Here we define a class @code{circle} as a child of @code{graphical},
                   10656: with a field @code{circle-radius}; it defines new methods for the
                   10657: selectors @code{draw} and @code{init} (@code{init} is defined in
                   10658: @code{object}, the parent class of @code{graphical}).
1.1       anton    10659: 
1.78      anton    10660: Now we can create a circle in the dictionary with:
1.1       anton    10661: 
1.78      anton    10662: @example
                   10663: 50 circle : my-circle
                   10664: @end example
1.21      crook    10665: 
1.78      anton    10666: @noindent
                   10667: @code{:} invokes @code{init}, thus initializing the field
                   10668: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   10669: with:
1.1       anton    10670: 
1.78      anton    10671: @example
                   10672: 100 100 my-circle draw
                   10673: @end example
1.1       anton    10674: 
1.78      anton    10675: @cindex selector invocation, restrictions
                   10676: @cindex class definition, restrictions
                   10677: Note: You can only invoke a selector if the receiving object belongs to
                   10678: the class where the selector was defined or one of its descendents;
                   10679: e.g., you can invoke @code{draw} only for objects belonging to
                   10680: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   10681: mechanism will check if you try to invoke a selector that is not
                   10682: defined in this class hierarchy, so you'll get an error at compilation
                   10683: time.
1.1       anton    10684: 
                   10685: 
1.78      anton    10686: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   10687: @subsubsection The @file{oof.fs} base class
                   10688: @cindex @file{oof.fs} base class
1.1       anton    10689: 
1.78      anton    10690: When you define a class, you have to specify a parent class.  So how do
                   10691: you start defining classes? There is one class available from the start:
                   10692: @code{object}. You have to use it as ancestor for all classes. It is the
                   10693: only class that has no parent. Classes are also objects, except that
                   10694: they don't have instance variables; class manipulation such as
                   10695: inheritance or changing definitions of a class is handled through
                   10696: selectors of the class @code{object}.
1.1       anton    10697: 
1.78      anton    10698: @code{object} provides a number of selectors:
1.1       anton    10699: 
1.78      anton    10700: @itemize @bullet
                   10701: @item
                   10702: @code{class} for subclassing, @code{definitions} to add definitions
                   10703: later on, and @code{class?} to get type informations (is the class a
                   10704: subclass of the class passed on the stack?).
1.1       anton    10705: 
1.78      anton    10706: doc---object-class
                   10707: doc---object-definitions
                   10708: doc---object-class?
1.1       anton    10709: 
                   10710: 
1.26      crook    10711: @item
1.78      anton    10712: @code{init} and @code{dispose} as constructor and destructor of the
                   10713: object. @code{init} is invocated after the object's memory is allocated,
                   10714: while @code{dispose} also handles deallocation. Thus if you redefine
                   10715: @code{dispose}, you have to call the parent's dispose with @code{super
                   10716: dispose}, too.
                   10717: 
                   10718: doc---object-init
                   10719: doc---object-dispose
                   10720: 
1.1       anton    10721: 
1.26      crook    10722: @item
1.78      anton    10723: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   10724: @code{[]} to create named and unnamed objects and object arrays or
                   10725: object pointers.
                   10726: 
                   10727: doc---object-new
                   10728: doc---object-new[]
                   10729: doc---object-:
                   10730: doc---object-ptr
                   10731: doc---object-asptr
                   10732: doc---object-[]
                   10733: 
1.1       anton    10734: 
1.26      crook    10735: @item
1.78      anton    10736: @code{::} and @code{super} for explicit scoping. You should use explicit
                   10737: scoping only for super classes or classes with the same set of instance
                   10738: variables. Explicitly-scoped selectors use early binding.
1.21      crook    10739: 
1.78      anton    10740: doc---object-::
                   10741: doc---object-super
1.21      crook    10742: 
                   10743: 
1.26      crook    10744: @item
1.78      anton    10745: @code{self} to get the address of the object
1.21      crook    10746: 
1.78      anton    10747: doc---object-self
1.21      crook    10748: 
                   10749: 
1.78      anton    10750: @item
                   10751: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   10752: pointers and instance defers.
1.21      crook    10753: 
1.78      anton    10754: doc---object-bind
                   10755: doc---object-bound
                   10756: doc---object-link
                   10757: doc---object-is
1.21      crook    10758: 
                   10759: 
1.78      anton    10760: @item
                   10761: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   10762: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    10763: 
1.78      anton    10764: doc---object-'
                   10765: doc---object-postpone
1.21      crook    10766: 
                   10767: 
1.78      anton    10768: @item
                   10769: @code{with} and @code{endwith} to select the active object from the
                   10770: stack, and enable its scope. Using @code{with} and @code{endwith}
                   10771: also allows you to create code using selector @code{postpone} without being
                   10772: trapped by the state-smart objects.
1.21      crook    10773: 
1.78      anton    10774: doc---object-with
                   10775: doc---object-endwith
1.21      crook    10776: 
                   10777: 
1.78      anton    10778: @end itemize
1.21      crook    10779: 
1.78      anton    10780: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   10781: @subsubsection Class Declaration
                   10782: @cindex class declaration
1.21      crook    10783: 
1.78      anton    10784: @itemize @bullet
                   10785: @item
                   10786: Instance variables
1.21      crook    10787: 
1.78      anton    10788: doc---oof-var
1.21      crook    10789: 
                   10790: 
1.78      anton    10791: @item
                   10792: Object pointers
1.21      crook    10793: 
1.78      anton    10794: doc---oof-ptr
                   10795: doc---oof-asptr
1.21      crook    10796: 
                   10797: 
1.78      anton    10798: @item
                   10799: Instance defers
1.21      crook    10800: 
1.78      anton    10801: doc---oof-defer
1.21      crook    10802: 
                   10803: 
1.78      anton    10804: @item
                   10805: Method selectors
1.21      crook    10806: 
1.78      anton    10807: doc---oof-early
                   10808: doc---oof-method
1.21      crook    10809: 
                   10810: 
1.78      anton    10811: @item
                   10812: Class-wide variables
1.21      crook    10813: 
1.78      anton    10814: doc---oof-static
1.21      crook    10815: 
                   10816: 
1.78      anton    10817: @item
                   10818: End declaration
1.1       anton    10819: 
1.78      anton    10820: doc---oof-how:
                   10821: doc---oof-class;
1.21      crook    10822: 
                   10823: 
1.78      anton    10824: @end itemize
1.21      crook    10825: 
1.78      anton    10826: @c -------------------------------------------------------------
                   10827: @node Class Implementation,  , Class Declaration, OOF
                   10828: @subsubsection Class Implementation
                   10829: @cindex class implementation
1.21      crook    10830: 
1.78      anton    10831: @c -------------------------------------------------------------
                   10832: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   10833: @subsection The @file{mini-oof.fs} model
                   10834: @cindex mini-oof
1.21      crook    10835: 
1.78      anton    10836: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    10837: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    10838: and reduces to the bare minimum of features. This is based on a posting
                   10839: of Bernd Paysan in comp.lang.forth.
1.21      crook    10840: 
1.78      anton    10841: @menu
                   10842: * Basic Mini-OOF Usage::        
                   10843: * Mini-OOF Example::            
                   10844: * Mini-OOF Implementation::     
                   10845: @end menu
1.21      crook    10846: 
1.78      anton    10847: @c -------------------------------------------------------------
                   10848: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   10849: @subsubsection Basic @file{mini-oof.fs} Usage
                   10850: @cindex mini-oof usage
1.21      crook    10851: 
1.78      anton    10852: There is a base class (@code{class}, which allocates one cell for the
                   10853: object pointer) plus seven other words: to define a method, a variable,
                   10854: a class; to end a class, to resolve binding, to allocate an object and
                   10855: to compile a class method.
                   10856: @comment TODO better description of the last one
1.26      crook    10857: 
1.21      crook    10858: 
1.78      anton    10859: doc-object
                   10860: doc-method
                   10861: doc-var
                   10862: doc-class
                   10863: doc-end-class
                   10864: doc-defines
                   10865: doc-new
                   10866: doc-::
1.21      crook    10867: 
                   10868: 
                   10869: 
1.78      anton    10870: @c -------------------------------------------------------------
                   10871: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   10872: @subsubsection Mini-OOF Example
                   10873: @cindex mini-oof example
1.1       anton    10874: 
1.78      anton    10875: A short example shows how to use this package. This example, in slightly
                   10876: extended form, is supplied as @file{moof-exm.fs}
                   10877: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   10878: 
1.26      crook    10879: @example
1.78      anton    10880: object class
                   10881:   method init
                   10882:   method draw
                   10883: end-class graphical
1.26      crook    10884: @end example
1.20      pazsan   10885: 
1.78      anton    10886: This code defines a class @code{graphical} with an
                   10887: operation @code{draw}.  We can perform the operation
                   10888: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   10889: 
1.26      crook    10890: @example
1.78      anton    10891: 100 100 t-rex draw
1.26      crook    10892: @end example
1.12      anton    10893: 
1.78      anton    10894: where @code{t-rex} is an object or object pointer, created with e.g.
                   10895: @code{graphical new Constant t-rex}.
1.12      anton    10896: 
1.78      anton    10897: For concrete graphical objects, we define child classes of the
                   10898: class @code{graphical}, e.g.:
1.12      anton    10899: 
1.26      crook    10900: @example
                   10901: graphical class
1.78      anton    10902:   cell var circle-radius
                   10903: end-class circle \ "graphical" is the parent class
1.12      anton    10904: 
1.78      anton    10905: :noname ( x y -- )
                   10906:   circle-radius @@ draw-circle ; circle defines draw
                   10907: :noname ( r -- )
                   10908:   circle-radius ! ; circle defines init
                   10909: @end example
1.12      anton    10910: 
1.78      anton    10911: There is no implicit init method, so we have to define one. The creation
                   10912: code of the object now has to call init explicitely.
1.21      crook    10913: 
1.78      anton    10914: @example
                   10915: circle new Constant my-circle
                   10916: 50 my-circle init
1.12      anton    10917: @end example
                   10918: 
1.78      anton    10919: It is also possible to add a function to create named objects with
                   10920: automatic call of @code{init}, given that all objects have @code{init}
                   10921: on the same place:
1.38      anton    10922: 
1.78      anton    10923: @example
                   10924: : new: ( .. o "name" -- )
                   10925:     new dup Constant init ;
                   10926: 80 circle new: large-circle
                   10927: @end example
1.12      anton    10928: 
1.78      anton    10929: We can draw this new circle at (100,100) with:
1.12      anton    10930: 
1.78      anton    10931: @example
                   10932: 100 100 my-circle draw
                   10933: @end example
1.12      anton    10934: 
1.78      anton    10935: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   10936: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    10937: 
1.78      anton    10938: Object-oriented systems with late binding typically use a
                   10939: ``vtable''-approach: the first variable in each object is a pointer to a
                   10940: table, which contains the methods as function pointers. The vtable
                   10941: may also contain other information.
1.12      anton    10942: 
1.79      anton    10943: So first, let's declare selectors:
1.37      anton    10944: 
                   10945: @example
1.79      anton    10946: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    10947:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   10948: @end example
1.37      anton    10949: 
1.79      anton    10950: During selector declaration, the number of selectors and instance
                   10951: variables is on the stack (in address units). @code{method} creates one
                   10952: selector and increments the selector number. To execute a selector, it
1.78      anton    10953: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    10954: executes the method @i{xt} stored there. Each selector takes the object
                   10955: it is invoked with as top of stack parameter; it passes the parameters
                   10956: (including the object) unchanged to the appropriate method which should
1.78      anton    10957: consume that object.
1.37      anton    10958: 
1.78      anton    10959: Now, we also have to declare instance variables
1.37      anton    10960: 
1.78      anton    10961: @example
1.79      anton    10962: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    10963:   DOES> ( o -- addr ) @@ + ;
1.37      anton    10964: @end example
                   10965: 
1.78      anton    10966: As before, a word is created with the current offset. Instance
                   10967: variables can have different sizes (cells, floats, doubles, chars), so
                   10968: all we do is take the size and add it to the offset. If your machine
                   10969: has alignment restrictions, put the proper @code{aligned} or
                   10970: @code{faligned} before the variable, to adjust the variable
                   10971: offset. That's why it is on the top of stack.
1.37      anton    10972: 
1.78      anton    10973: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    10974: 
1.78      anton    10975: @example
                   10976: Create object  1 cells , 2 cells ,
1.79      anton    10977: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    10978: @end example
1.12      anton    10979: 
1.78      anton    10980: For inheritance, the vtable of the parent object has to be
                   10981: copied when a new, derived class is declared. This gives all the
                   10982: methods of the parent class, which can be overridden, though.
1.12      anton    10983: 
1.78      anton    10984: @example
1.79      anton    10985: : end-class  ( class selectors vars "name" -- )
1.78      anton    10986:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   10987:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   10988: @end example
1.12      anton    10989: 
1.78      anton    10990: The first line creates the vtable, initialized with
                   10991: @code{noop}s. The second line is the inheritance mechanism, it
                   10992: copies the xts from the parent vtable.
1.12      anton    10993: 
1.78      anton    10994: We still have no way to define new methods, let's do that now:
1.12      anton    10995: 
1.26      crook    10996: @example
1.79      anton    10997: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    10998: @end example
1.12      anton    10999: 
1.78      anton    11000: To allocate a new object, we need a word, too:
1.12      anton    11001: 
1.78      anton    11002: @example
                   11003: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11004: @end example
                   11005: 
1.78      anton    11006: Sometimes derived classes want to access the method of the
                   11007: parent object. There are two ways to achieve this with Mini-OOF:
                   11008: first, you could use named words, and second, you could look up the
                   11009: vtable of the parent object.
1.12      anton    11010: 
1.78      anton    11011: @example
                   11012: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11013: @end example
1.12      anton    11014: 
                   11015: 
1.78      anton    11016: Nothing can be more confusing than a good example, so here is
                   11017: one. First let's declare a text object (called
                   11018: @code{button}), that stores text and position:
1.12      anton    11019: 
1.78      anton    11020: @example
                   11021: object class
                   11022:   cell var text
                   11023:   cell var len
                   11024:   cell var x
                   11025:   cell var y
                   11026:   method init
                   11027:   method draw
                   11028: end-class button
                   11029: @end example
1.12      anton    11030: 
1.78      anton    11031: @noindent
                   11032: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11033: 
1.26      crook    11034: @example
1.78      anton    11035: :noname ( o -- )
                   11036:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11037:  button defines draw
                   11038: :noname ( addr u o -- )
                   11039:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11040:  button defines init
1.26      crook    11041: @end example
1.12      anton    11042: 
1.78      anton    11043: @noindent
                   11044: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11045: new data and no new selectors:
1.78      anton    11046: 
                   11047: @example
                   11048: button class
                   11049: end-class bold-button
1.12      anton    11050: 
1.78      anton    11051: : bold   27 emit ." [1m" ;
                   11052: : normal 27 emit ." [0m" ;
                   11053: @end example
1.1       anton    11054: 
1.78      anton    11055: @noindent
                   11056: The class @code{bold-button} has a different draw method to
                   11057: @code{button}, but the new method is defined in terms of the draw method
                   11058: for @code{button}:
1.20      pazsan   11059: 
1.78      anton    11060: @example
                   11061: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11062: @end example
1.21      crook    11063: 
1.78      anton    11064: @noindent
1.79      anton    11065: Finally, create two objects and apply selectors:
1.21      crook    11066: 
1.26      crook    11067: @example
1.78      anton    11068: button new Constant foo
                   11069: s" thin foo" foo init
                   11070: page
                   11071: foo draw
                   11072: bold-button new Constant bar
                   11073: s" fat bar" bar init
                   11074: 1 bar y !
                   11075: bar draw
1.26      crook    11076: @end example
1.21      crook    11077: 
                   11078: 
1.78      anton    11079: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11080: @subsection Comparison with other object models
                   11081: @cindex comparison of object models
                   11082: @cindex object models, comparison
                   11083: 
                   11084: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11085: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11086: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11087: relation of the object models described here to two well-known and two
                   11088: closely-related (by the use of method maps) models.  Andras Zsoter
                   11089: helped us with this section.
                   11090: 
                   11091: @cindex Neon model
                   11092: The most popular model currently seems to be the Neon model (see
                   11093: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11094: 1997) by Andrew McKewan) but this model has a number of limitations
                   11095: @footnote{A longer version of this critique can be
                   11096: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11097: Dimensions, May 1997) by Anton Ertl.}:
                   11098: 
                   11099: @itemize @bullet
                   11100: @item
                   11101: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11102: to pass objects on the stack.
1.21      crook    11103: 
1.78      anton    11104: @item
                   11105: It requires that the selector parses the input stream (at
1.79      anton    11106: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11107: hard to find.
1.21      crook    11108: 
1.78      anton    11109: @item
1.79      anton    11110: It allows using every selector on every object; this eliminates the
                   11111: need for interfaces, but makes it harder to create efficient
                   11112: implementations.
1.78      anton    11113: @end itemize
1.21      crook    11114: 
1.78      anton    11115: @cindex Pountain's object-oriented model
                   11116: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11117: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11118: object-oriented programming, because it hardly deals with late
                   11119: binding. Instead, it focuses on features like information hiding and
                   11120: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11121: 
1.78      anton    11122: @cindex Zsoter's object-oriented model
1.79      anton    11123: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11124: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11125: describes a model that makes heavy use of an active object (like
                   11126: @code{this} in @file{objects.fs}): The active object is not only used
                   11127: for accessing all fields, but also specifies the receiving object of
                   11128: every selector invocation; you have to change the active object
                   11129: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11130: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11131: the method entry point is unnecessary with Zsoter's model, because the
                   11132: receiving object is the active object already. On the other hand, the
                   11133: explicit change is absolutely necessary in that model, because otherwise
                   11134: no one could ever change the active object. An ANS Forth implementation
                   11135: of this model is available through
                   11136: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11137: 
1.78      anton    11138: @cindex @file{oof.fs}, differences to other models
                   11139: The @file{oof.fs} model combines information hiding and overloading
                   11140: resolution (by keeping names in various word lists) with object-oriented
                   11141: programming. It sets the active object implicitly on method entry, but
                   11142: also allows explicit changing (with @code{>o...o>} or with
                   11143: @code{with...endwith}). It uses parsing and state-smart objects and
                   11144: classes for resolving overloading and for early binding: the object or
                   11145: class parses the selector and determines the method from this. If the
                   11146: selector is not parsed by an object or class, it performs a call to the
                   11147: selector for the active object (late binding), like Zsoter's model.
                   11148: Fields are always accessed through the active object. The big
                   11149: disadvantage of this model is the parsing and the state-smartness, which
                   11150: reduces extensibility and increases the opportunities for subtle bugs;
                   11151: essentially, you are only safe if you never tick or @code{postpone} an
                   11152: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11153: 
1.78      anton    11154: @cindex @file{mini-oof.fs}, differences to other models
                   11155: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11156: version of the @file{objects.fs} model, but syntactically it is a
                   11157: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11158: 
                   11159: 
1.78      anton    11160: @c -------------------------------------------------------------
                   11161: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
                   11162: @section Programming Tools
                   11163: @cindex programming tools
1.21      crook    11164: 
1.78      anton    11165: @c !! move this and assembler down below OO stuff.
1.21      crook    11166: 
1.78      anton    11167: @menu
                   11168: * Examining::                   
                   11169: * Forgetting words::            
                   11170: * Debugging::                   Simple and quick.
                   11171: * Assertions::                  Making your programs self-checking.
                   11172: * Singlestep Debugger::         Executing your program word by word.
                   11173: @end menu
1.21      crook    11174: 
1.78      anton    11175: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11176: @subsection Examining data and code
                   11177: @cindex examining data and code
                   11178: @cindex data examination
                   11179: @cindex code examination
1.44      crook    11180: 
1.78      anton    11181: The following words inspect the stack non-destructively:
1.21      crook    11182: 
1.78      anton    11183: doc-.s
                   11184: doc-f.s
1.44      crook    11185: 
1.78      anton    11186: There is a word @code{.r} but it does @i{not} display the return stack!
                   11187: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    11188: 
1.78      anton    11189: doc-depth
                   11190: doc-fdepth
                   11191: doc-clearstack
1.21      crook    11192: 
1.78      anton    11193: The following words inspect memory.
1.21      crook    11194: 
1.78      anton    11195: doc-?
                   11196: doc-dump
1.21      crook    11197: 
1.78      anton    11198: And finally, @code{see} allows to inspect code:
1.21      crook    11199: 
1.78      anton    11200: doc-see
                   11201: doc-xt-see
1.111     anton    11202: doc-simple-see
                   11203: doc-simple-see-range
1.21      crook    11204: 
1.78      anton    11205: @node Forgetting words, Debugging, Examining, Programming Tools
                   11206: @subsection Forgetting words
                   11207: @cindex words, forgetting
                   11208: @cindex forgeting words
1.21      crook    11209: 
1.78      anton    11210: @c  anton: other, maybe better places for this subsection: Defining Words;
                   11211: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    11212: 
1.78      anton    11213: Forth allows you to forget words (and everything that was alloted in the
                   11214: dictonary after them) in a LIFO manner.
1.21      crook    11215: 
1.78      anton    11216: doc-marker
1.21      crook    11217: 
1.78      anton    11218: The most common use of this feature is during progam development: when
                   11219: you change a source file, forget all the words it defined and load it
                   11220: again (since you also forget everything defined after the source file
                   11221: was loaded, you have to reload that, too).  Note that effects like
                   11222: storing to variables and destroyed system words are not undone when you
                   11223: forget words.  With a system like Gforth, that is fast enough at
                   11224: starting up and compiling, I find it more convenient to exit and restart
                   11225: Gforth, as this gives me a clean slate.
1.21      crook    11226: 
1.78      anton    11227: Here's an example of using @code{marker} at the start of a source file
                   11228: that you are debugging; it ensures that you only ever have one copy of
                   11229: the file's definitions compiled at any time:
1.21      crook    11230: 
1.78      anton    11231: @example
                   11232: [IFDEF] my-code
                   11233:     my-code
                   11234: [ENDIF]
1.26      crook    11235: 
1.78      anton    11236: marker my-code
                   11237: init-included-files
1.21      crook    11238: 
1.78      anton    11239: \ .. definitions start here
                   11240: \ .
                   11241: \ .
                   11242: \ end
                   11243: @end example
1.21      crook    11244: 
1.26      crook    11245: 
1.78      anton    11246: @node Debugging, Assertions, Forgetting words, Programming Tools
                   11247: @subsection Debugging
                   11248: @cindex debugging
1.21      crook    11249: 
1.78      anton    11250: Languages with a slow edit/compile/link/test development loop tend to
                   11251: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    11252: 
1.78      anton    11253: A much better (faster) way in fast-compiling languages is to add
                   11254: printing code at well-selected places, let the program run, look at
                   11255: the output, see where things went wrong, add more printing code, etc.,
                   11256: until the bug is found.
1.21      crook    11257: 
1.78      anton    11258: The simple debugging aids provided in @file{debugs.fs}
                   11259: are meant to support this style of debugging.
1.21      crook    11260: 
1.78      anton    11261: The word @code{~~} prints debugging information (by default the source
                   11262: location and the stack contents). It is easy to insert. If you use Emacs
                   11263: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   11264: query-replace them with nothing). The deferred words
1.101     anton    11265: @code{printdebugdata} and @code{.debugline} control the output of
1.78      anton    11266: @code{~~}. The default source location output format works well with
                   11267: Emacs' compilation mode, so you can step through the program at the
                   11268: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   11269: is that you can step in any direction and you know where the crash has
                   11270: happened or where the strange data has occurred).
1.21      crook    11271: 
1.78      anton    11272: doc-~~
                   11273: doc-printdebugdata
1.101     anton    11274: doc-.debugline
1.21      crook    11275: 
1.106     anton    11276: @cindex filenames in @code{~~} output
                   11277: @code{~~} (and assertions) will usually print the wrong file name if a
                   11278: marker is executed in the same file after their occurance.  They will
                   11279: print @samp{*somewhere*} as file name if a marker is executed in the
                   11280: same file before their occurance.
                   11281: 
                   11282: 
1.78      anton    11283: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   11284: @subsection Assertions
                   11285: @cindex assertions
1.21      crook    11286: 
1.78      anton    11287: It is a good idea to make your programs self-checking, especially if you
                   11288: make an assumption that may become invalid during maintenance (for
                   11289: example, that a certain field of a data structure is never zero). Gforth
                   11290: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    11291: 
                   11292: @example
1.78      anton    11293: assert( @i{flag} )
1.26      crook    11294: @end example
                   11295: 
1.78      anton    11296: The code between @code{assert(} and @code{)} should compute a flag, that
                   11297: should be true if everything is alright and false otherwise. It should
                   11298: not change anything else on the stack. The overall stack effect of the
                   11299: assertion is @code{( -- )}. E.g.
1.21      crook    11300: 
1.26      crook    11301: @example
1.78      anton    11302: assert( 1 1 + 2 = ) \ what we learn in school
                   11303: assert( dup 0<> ) \ assert that the top of stack is not zero
                   11304: assert( false ) \ this code should not be reached
1.21      crook    11305: @end example
                   11306: 
1.78      anton    11307: The need for assertions is different at different times. During
                   11308: debugging, we want more checking, in production we sometimes care more
                   11309: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   11310: becomes a comment. Depending on the importance of an assertion and the
                   11311: time it takes to check it, you may want to turn off some assertions and
                   11312: keep others turned on. Gforth provides several levels of assertions for
                   11313: this purpose:
                   11314: 
                   11315: 
                   11316: doc-assert0(
                   11317: doc-assert1(
                   11318: doc-assert2(
                   11319: doc-assert3(
                   11320: doc-assert(
                   11321: doc-)
1.21      crook    11322: 
                   11323: 
1.78      anton    11324: The variable @code{assert-level} specifies the highest assertions that
                   11325: are turned on. I.e., at the default @code{assert-level} of one,
                   11326: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   11327: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    11328: 
1.78      anton    11329: The value of @code{assert-level} is evaluated at compile-time, not at
                   11330: run-time. Therefore you cannot turn assertions on or off at run-time;
                   11331: you have to set the @code{assert-level} appropriately before compiling a
                   11332: piece of code. You can compile different pieces of code at different
                   11333: @code{assert-level}s (e.g., a trusted library at level 1 and
                   11334: newly-written code at level 3).
1.26      crook    11335: 
                   11336: 
1.78      anton    11337: doc-assert-level
1.26      crook    11338: 
                   11339: 
1.78      anton    11340: If an assertion fails, a message compatible with Emacs' compilation mode
                   11341: is produced and the execution is aborted (currently with @code{ABORT"}.
                   11342: If there is interest, we will introduce a special throw code. But if you
                   11343: intend to @code{catch} a specific condition, using @code{throw} is
                   11344: probably more appropriate than an assertion).
1.106     anton    11345: 
                   11346: @cindex filenames in assertion output
                   11347: Assertions (and @code{~~}) will usually print the wrong file name if a
                   11348: marker is executed in the same file after their occurance.  They will
                   11349: print @samp{*somewhere*} as file name if a marker is executed in the
                   11350: same file before their occurance.
1.44      crook    11351: 
1.78      anton    11352: Definitions in ANS Forth for these assertion words are provided
                   11353: in @file{compat/assert.fs}.
1.26      crook    11354: 
1.44      crook    11355: 
1.78      anton    11356: @node Singlestep Debugger,  , Assertions, Programming Tools
                   11357: @subsection Singlestep Debugger
                   11358: @cindex singlestep Debugger
                   11359: @cindex debugging Singlestep
1.44      crook    11360: 
1.112     anton    11361: The singlestep debugger does not work in this release.
                   11362: 
1.78      anton    11363: When you create a new word there's often the need to check whether it
                   11364: behaves correctly or not. You can do this by typing @code{dbg
                   11365: badword}. A debug session might look like this:
1.26      crook    11366: 
1.78      anton    11367: @example
                   11368: : badword 0 DO i . LOOP ;  ok
                   11369: 2 dbg badword 
                   11370: : badword  
                   11371: Scanning code...
1.44      crook    11372: 
1.78      anton    11373: Nesting debugger ready!
1.44      crook    11374: 
1.78      anton    11375: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   11376: 400D4740  8049F68 DO             -> [ 0 ] 
                   11377: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   11378: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   11379: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11380: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   11381: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   11382: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11383: 400D4758  804B384 ;              ->  ok
                   11384: @end example
1.21      crook    11385: 
1.78      anton    11386: Each line displayed is one step. You always have to hit return to
                   11387: execute the next word that is displayed. If you don't want to execute
                   11388: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   11389: an overview what keys are available:
1.44      crook    11390: 
1.78      anton    11391: @table @i
1.44      crook    11392: 
1.78      anton    11393: @item @key{RET}
                   11394: Next; Execute the next word.
1.21      crook    11395: 
1.78      anton    11396: @item n
                   11397: Nest; Single step through next word.
1.44      crook    11398: 
1.78      anton    11399: @item u
                   11400: Unnest; Stop debugging and execute rest of word. If we got to this word
                   11401: with nest, continue debugging with the calling word.
1.44      crook    11402: 
1.78      anton    11403: @item d
                   11404: Done; Stop debugging and execute rest.
1.21      crook    11405: 
1.78      anton    11406: @item s
                   11407: Stop; Abort immediately.
1.44      crook    11408: 
1.78      anton    11409: @end table
1.44      crook    11410: 
1.78      anton    11411: Debugging large application with this mechanism is very difficult, because
                   11412: you have to nest very deeply into the program before the interesting part
                   11413: begins. This takes a lot of time. 
1.26      crook    11414: 
1.78      anton    11415: To do it more directly put a @code{BREAK:} command into your source code.
                   11416: When program execution reaches @code{BREAK:} the single step debugger is
                   11417: invoked and you have all the features described above.
1.44      crook    11418: 
1.78      anton    11419: If you have more than one part to debug it is useful to know where the
                   11420: program has stopped at the moment. You can do this by the 
                   11421: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   11422: string is typed out when the ``breakpoint'' is reached.
1.44      crook    11423: 
1.26      crook    11424: 
1.78      anton    11425: doc-dbg
                   11426: doc-break:
                   11427: doc-break"
1.44      crook    11428: 
                   11429: 
1.26      crook    11430: 
1.78      anton    11431: @c -------------------------------------------------------------
                   11432: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   11433: @section Assembler and Code Words
                   11434: @cindex assembler
                   11435: @cindex code words
1.44      crook    11436: 
1.78      anton    11437: @menu
                   11438: * Code and ;code::              
                   11439: * Common Assembler::            Assembler Syntax
                   11440: * Common Disassembler::         
                   11441: * 386 Assembler::               Deviations and special cases
                   11442: * Alpha Assembler::             Deviations and special cases
                   11443: * MIPS assembler::              Deviations and special cases
                   11444: * Other assemblers::            How to write them
                   11445: @end menu
1.21      crook    11446: 
1.78      anton    11447: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   11448: @subsection @code{Code} and @code{;code}
1.26      crook    11449: 
1.78      anton    11450: Gforth provides some words for defining primitives (words written in
                   11451: machine code), and for defining the machine-code equivalent of
                   11452: @code{DOES>}-based defining words. However, the machine-independent
                   11453: nature of Gforth poses a few problems: First of all, Gforth runs on
                   11454: several architectures, so it can provide no standard assembler. What's
                   11455: worse is that the register allocation not only depends on the processor,
                   11456: but also on the @code{gcc} version and options used.
1.44      crook    11457: 
1.78      anton    11458: The words that Gforth offers encapsulate some system dependences (e.g.,
                   11459: the header structure), so a system-independent assembler may be used in
                   11460: Gforth. If you do not have an assembler, you can compile machine code
                   11461: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   11462: because these words emit stuff in @i{data} space; it works because
                   11463: Gforth has unified code/data spaces. Assembler isn't likely to be
                   11464: portable anyway.}.
1.21      crook    11465: 
1.44      crook    11466: 
1.78      anton    11467: doc-assembler
                   11468: doc-init-asm
                   11469: doc-code
                   11470: doc-end-code
                   11471: doc-;code
                   11472: doc-flush-icache
1.44      crook    11473: 
1.21      crook    11474: 
1.78      anton    11475: If @code{flush-icache} does not work correctly, @code{code} words
                   11476: etc. will not work (reliably), either.
1.44      crook    11477: 
1.78      anton    11478: The typical usage of these @code{code} words can be shown most easily by
                   11479: analogy to the equivalent high-level defining words:
1.44      crook    11480: 
1.78      anton    11481: @example
                   11482: : foo                              code foo
                   11483:    <high-level Forth words>              <assembler>
                   11484: ;                                  end-code
                   11485:                                 
                   11486: : bar                              : bar
                   11487:    <high-level Forth words>           <high-level Forth words>
                   11488:    CREATE                             CREATE
                   11489:       <high-level Forth words>           <high-level Forth words>
                   11490:    DOES>                              ;code
                   11491:       <high-level Forth words>           <assembler>
                   11492: ;                                  end-code
                   11493: @end example
1.21      crook    11494: 
1.78      anton    11495: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44      crook    11496: 
1.78      anton    11497: @cindex registers of the inner interpreter
                   11498: In the assembly code you will want to refer to the inner interpreter's
                   11499: registers (e.g., the data stack pointer) and you may want to use other
                   11500: registers for temporary storage. Unfortunately, the register allocation
                   11501: is installation-dependent.
1.44      crook    11502: 
1.78      anton    11503: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100     anton    11504: (return stack pointer) may be in different places in @code{gforth} and
                   11505: @code{gforth-fast}, or different installations.  This means that you
                   11506: cannot write a @code{NEXT} routine that works reliably on both versions
                   11507: or different installations; so for doing @code{NEXT}, I recommend
                   11508: jumping to @code{' noop >code-address}, which contains nothing but a
                   11509: @code{NEXT}.
1.21      crook    11510: 
1.78      anton    11511: For general accesses to the inner interpreter's registers, the easiest
                   11512: solution is to use explicit register declarations (@pxref{Explicit Reg
                   11513: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
                   11514: all of the inner interpreter's registers: You have to compile Gforth
                   11515: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
                   11516: the appropriate declarations must be present in the @code{machine.h}
                   11517: file (see @code{mips.h} for an example; you can find a full list of all
                   11518: declarable register symbols with @code{grep register engine.c}). If you
                   11519: give explicit registers to all variables that are declared at the
                   11520: beginning of @code{engine()}, you should be able to use the other
                   11521: caller-saved registers for temporary storage. Alternatively, you can use
                   11522: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
                   11523: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
                   11524: reserve a register (however, this restriction on register allocation may
                   11525: slow Gforth significantly).
1.44      crook    11526: 
1.78      anton    11527: If this solution is not viable (e.g., because @code{gcc} does not allow
                   11528: you to explicitly declare all the registers you need), you have to find
                   11529: out by looking at the code where the inner interpreter's registers
                   11530: reside and which registers can be used for temporary storage. You can
                   11531: get an assembly listing of the engine's code with @code{make engine.s}.
1.44      crook    11532: 
1.78      anton    11533: In any case, it is good practice to abstract your assembly code from the
                   11534: actual register allocation. E.g., if the data stack pointer resides in
                   11535: register @code{$17}, create an alias for this register called @code{sp},
                   11536: and use that in your assembly code.
1.21      crook    11537: 
1.78      anton    11538: @cindex code words, portable
                   11539: Another option for implementing normal and defining words efficiently
                   11540: is to add the desired functionality to the source of Gforth. For normal
                   11541: words you just have to edit @file{primitives} (@pxref{Automatic
                   11542: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   11543: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   11544: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44      crook    11545: 
1.78      anton    11546: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   11547: @subsection Common Assembler
1.44      crook    11548: 
1.78      anton    11549: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   11550: instruction name follows the operands.
1.21      crook    11551: 
1.78      anton    11552: The operands are passed in the usual order (the same that is used in the
                   11553: manual of the architecture).  Since they all are Forth words, they have
                   11554: to be separated by spaces; you can also use Forth words to compute the
                   11555: operands.
1.44      crook    11556: 
1.78      anton    11557: The instruction names usually end with a @code{,}.  This makes it easier
                   11558: to visually separate instructions if you put several of them on one
                   11559: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    11560: 
1.78      anton    11561: Registers are usually specified by number; e.g., (decimal) @code{11}
                   11562: specifies registers R11 and F11 on the Alpha architecture (which one,
                   11563: depends on the instruction).  The usual names are also available, e.g.,
                   11564: @code{s2} for R11 on Alpha.
1.21      crook    11565: 
1.78      anton    11566: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   11567: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   11568: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   11569: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   11570: conditions are specified in a way specific to each assembler.
1.1       anton    11571: 
1.78      anton    11572: Note that the register assignments of the Gforth engine can change
                   11573: between Gforth versions, or even between different compilations of the
                   11574: same Gforth version (e.g., if you use a different GCC version).  So if
                   11575: you want to refer to Gforth's registers (e.g., the stack pointer or
                   11576: TOS), I recommend defining your own words for refering to these
                   11577: registers, and using them later on; then you can easily adapt to a
                   11578: changed register assignment.  The stability of the register assignment
                   11579: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1       anton    11580: 
1.100     anton    11581: The most common use of these registers is to dispatch to the next word
                   11582: (the @code{next} routine).  A portable way to do this is to jump to
                   11583: @code{' noop >code-address} (of course, this is less efficient than
                   11584: integrating the @code{next} code and scheduling it well).
1.1       anton    11585: 
1.96      anton    11586: Another difference between Gforth version is that the top of stack is
                   11587: kept in memory in @code{gforth} and, on most platforms, in a register in
                   11588: @code{gforth-fast}.
                   11589: 
1.78      anton    11590: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   11591: @subsection Common Disassembler
1.1       anton    11592: 
1.78      anton    11593: You can disassemble a @code{code} word with @code{see}
                   11594: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    11595: 
1.78      anton    11596: doc-disasm
1.44      crook    11597: 
1.78      anton    11598: The disassembler generally produces output that can be fed into the
                   11599: assembler (i.e., same syntax, etc.).  It also includes additional
                   11600: information in comments.  In particular, the address of the instruction
                   11601: is given in a comment before the instruction.
1.1       anton    11602: 
1.78      anton    11603: @code{See} may display more or less than the actual code of the word,
                   11604: because the recognition of the end of the code is unreliable.  You can
                   11605: use @code{disasm} if it did not display enough.  It may display more, if
                   11606: the code word is not immediately followed by a named word.  If you have
                   11607: something else there, you can follow the word with @code{align last @ ,}
                   11608: to ensure that the end is recognized.
1.21      crook    11609: 
1.78      anton    11610: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   11611: @subsection 386 Assembler
1.44      crook    11612: 
1.78      anton    11613: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   11614: available under GPL, and originally part of bigFORTH.
1.21      crook    11615: 
1.78      anton    11616: The 386 disassembler included in Gforth was written by Andrew McKewan
                   11617: and is in the public domain.
1.21      crook    11618: 
1.91      anton    11619: The disassembler displays code in an Intel-like prefix syntax.
1.21      crook    11620: 
1.78      anton    11621: The assembler uses a postfix syntax with reversed parameters.
1.1       anton    11622: 
1.78      anton    11623: The assembler includes all instruction of the Athlon, i.e. 486 core
                   11624: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   11625: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   11626: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    11627: 
1.78      anton    11628: There are several prefixes to switch between different operation sizes,
                   11629: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   11630: double-word accesses. Addressing modes can be switched with @code{.wa}
                   11631: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   11632: need a prefix for byte register names (@code{AL} et al).
1.1       anton    11633: 
1.78      anton    11634: For floating point operations, the prefixes are @code{.fs} (IEEE
                   11635: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   11636: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21      crook    11637: 
1.78      anton    11638: The MMX opcodes don't have size prefixes, they are spelled out like in
                   11639: the Intel assembler. Instead of move from and to memory, there are
                   11640: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    11641: 
1.78      anton    11642: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   11643: ax.  Immediate values are indicated by postfixing them with @code{#},
1.91      anton    11644: e.g., @code{3 #}.  Here are some examples of addressing modes in various
                   11645: syntaxes:
1.21      crook    11646: 
1.26      crook    11647: @example
1.91      anton    11648: Gforth          Intel (NASM)   AT&T (gas)      Name
                   11649: .w ax           ax             %ax             register (16 bit)
                   11650: ax              eax            %eax            register (32 bit)
                   11651: 3 #             offset 3       $3              immediate
                   11652: 1000 #)         byte ptr 1000  1000            displacement
                   11653: bx )            [ebx]          (%ebx)          base
                   11654: 100 di d)       100[edi]       100(%edi)       base+displacement
                   11655: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
                   11656: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
                   11657: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
                   11658: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
                   11659: @end example
                   11660: 
                   11661: You can use @code{L)} and @code{LI)} instead of @code{D)} and
                   11662: @code{DI)} to enforce 32-bit displacement fields (useful for
                   11663: later patching).
1.21      crook    11664: 
1.78      anton    11665: Some example of instructions are:
1.1       anton    11666: 
                   11667: @example
1.78      anton    11668: ax bx mov             \ move ebx,eax
                   11669: 3 # ax mov            \ mov eax,3
                   11670: 100 di ) ax mov       \ mov eax,100[edi]
                   11671: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   11672: .w ax bx mov          \ mov bx,ax
1.1       anton    11673: @end example
                   11674: 
1.78      anton    11675: The following forms are supported for binary instructions:
1.1       anton    11676: 
                   11677: @example
1.78      anton    11678: <reg> <reg> <inst>
                   11679: <n> # <reg> <inst>
                   11680: <mem> <reg> <inst>
                   11681: <reg> <mem> <inst>
1.1       anton    11682: @end example
                   11683: 
1.78      anton    11684: Immediate to memory is not supported.  The shift/rotate syntax is:
1.1       anton    11685: 
1.26      crook    11686: @example
1.78      anton    11687: <reg/mem> 1 # shl \ shortens to shift without immediate
                   11688: <reg/mem> 4 # shl
                   11689: <reg/mem> cl shl
1.26      crook    11690: @end example
1.1       anton    11691: 
1.78      anton    11692: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   11693: the byte version.
1.1       anton    11694: 
1.78      anton    11695: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   11696: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   11697: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   11698: when @code{assembler} is in front of @code{forth} in the search path,
                   11699: e.g., in @code{code} words).  Currently the control structure words use
                   11700: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   11701: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    11702: 
1.78      anton    11703: Here is an example of a @code{code} word (assumes that the stack pointer
                   11704: is in esi and the TOS is in ebx):
1.21      crook    11705: 
1.26      crook    11706: @example
1.78      anton    11707: code my+ ( n1 n2 -- n )
                   11708:     4 si D) bx add
                   11709:     4 # si add
                   11710:     Next
                   11711: end-code
1.26      crook    11712: @end example
1.21      crook    11713: 
1.78      anton    11714: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   11715: @subsection Alpha Assembler
1.21      crook    11716: 
1.78      anton    11717: The Alpha assembler and disassembler were originally written by Bernd
                   11718: Thallner.
1.26      crook    11719: 
1.78      anton    11720: The register names @code{a0}--@code{a5} are not available to avoid
                   11721: shadowing hex numbers.
1.2       jwilke   11722: 
1.78      anton    11723: Immediate forms of arithmetic instructions are distinguished by a
                   11724: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   11725: does not count as arithmetic instruction).
1.2       jwilke   11726: 
1.78      anton    11727: You have to specify all operands to an instruction, even those that
                   11728: other assemblers consider optional, e.g., the destination register for
                   11729: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   11730: 
1.78      anton    11731: You can specify conditions for @code{if,} by removing the first @code{b}
                   11732: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   11733: 
1.26      crook    11734: @example
1.78      anton    11735: 11 fgt if, \ if F11>0e
                   11736:   ...
                   11737: endif,
1.26      crook    11738: @end example
1.2       jwilke   11739: 
1.78      anton    11740: @code{fbgt,} gives @code{fgt}.  
                   11741: 
                   11742: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
                   11743: @subsection MIPS assembler
1.2       jwilke   11744: 
1.78      anton    11745: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   11746: 
1.78      anton    11747: Currently the assembler and disassembler only cover the MIPS-I
                   11748: architecture (R3000), and don't support FP instructions.
1.2       jwilke   11749: 
1.78      anton    11750: The register names @code{$a0}--@code{$a3} are not available to avoid
                   11751: shadowing hex numbers.
1.2       jwilke   11752: 
1.78      anton    11753: Because there is no way to distinguish registers from immediate values,
                   11754: you have to explicitly use the immediate forms of instructions, i.e.,
                   11755: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   11756: implicitly).
1.2       jwilke   11757: 
1.78      anton    11758: If the architecture manual specifies several formats for the instruction
                   11759: (e.g., for @code{jalr,}), you usually have to use the one with more
                   11760: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   11761: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   11762: 
1.78      anton    11763: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   11764: to fill it yourself (the simplest way is to use @code{nop,}), the
                   11765: assembler does not do it for you (unlike @command{as}).  Even
                   11766: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   11767: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   11768: and @code{then,} just specify branch targets, they are not affected.
1.2       jwilke   11769: 
1.78      anton    11770: Note that you must not put branches, jumps, or @code{li,} into the delay
                   11771: slot: @code{li,} may expand to several instructions, and control flow
                   11772: instructions may not be put into the branch delay slot in any case.
1.2       jwilke   11773: 
1.78      anton    11774: For branches the argument specifying the target is a relative address;
                   11775: You have to add the address of the delay slot to get the absolute
                   11776: address.
1.1       anton    11777: 
1.78      anton    11778: The MIPS architecture also has load delay slots and restrictions on
                   11779: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   11780: yourself to satisfy these restrictions, the assembler does not do it for
                   11781: you.
1.1       anton    11782: 
1.78      anton    11783: You can specify the conditions for @code{if,} etc. by taking a
                   11784: conditional branch and leaving away the @code{b} at the start and the
                   11785: @code{,} at the end.  E.g.,
1.1       anton    11786: 
1.26      crook    11787: @example
1.78      anton    11788: 4 5 eq if,
                   11789:   ... \ do something if $4 equals $5
                   11790: then,
1.26      crook    11791: @end example
1.1       anton    11792: 
1.78      anton    11793: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
                   11794: @subsection Other assemblers
                   11795: 
                   11796: If you want to contribute another assembler/disassembler, please contact
1.103     anton    11797: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
                   11798: an assembler already.  If you are writing them from scratch, please use
                   11799: a similar syntax style as the one we use (i.e., postfix, commas at the
                   11800: end of the instruction names, @pxref{Common Assembler}); make the output
                   11801: of the disassembler be valid input for the assembler, and keep the style
1.78      anton    11802: similar to the style we used.
                   11803: 
                   11804: Hints on implementation: The most important part is to have a good test
                   11805: suite that contains all instructions.  Once you have that, the rest is
                   11806: easy.  For actual coding you can take a look at
                   11807: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   11808: the assembler and disassembler, avoiding redundancy and some potential
                   11809: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   11810: example}) to get ideas how to factor a disassembler.
                   11811: 
                   11812: Start with the disassembler, because it's easier to reuse data from the
                   11813: disassembler for the assembler than the other way round.
1.1       anton    11814: 
1.78      anton    11815: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   11816: how simple it can be.
1.1       anton    11817: 
1.78      anton    11818: @c -------------------------------------------------------------
                   11819: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   11820:&n