Forth (programming language)
11012
225362303
2008-07-13T08:14:54Z
Mhx
1430794
/* Implementations */ White Lightening for the Commodore 64 is not an ANS Forth (it's dated 1984!)
{{ infobox programming language
| name = Forth
| paradigm = [[Procedural programming|Procedural]], [[stack-oriented programming language|stack-oriented]]
| year = 1970s
| designer = [[Charles H. Moore]]
| typing = typeless
| dialects = [[colorForth]], [[Open Firmware]]
| implementations = Forth, Inc., GNU Forth, MPE
| influenced_by = [[Burroughs large systems]], [[Lisp programming language|Lisp]], [[APL programming language|APL]]
| influenced = [[PostScript]],<ref>{{ cite book | others = Adobe Systems Inc. | title = PostScript Language - Tutorial and Cookbook | format = paperback | edition = First | year = 1985 | publisher = Addison-Wesley | language = English | id = ISBN 0-201-10179-3 | pages = 243 | chapter = First | quote = The PostScript language contains elements of many programming languages, but most closely resembles the Forth language. }}</ref> [[Factor (programming language)|Factor]], [[Joy (programming language)|Joy]], [[Cat (programming language)|Cat]]
}}
'''Forth''' is a [[structured programming|structured]] [[imperative programming|imperative]] [[stack-oriented programming language|stack-based]] [[computer programming|computer]] [[programming language]] and programming environment. Forth is sometimes spelled in all capital letters following the customary usage during its earlier years, although the name is not an [[acronym]].
A [[procedural programming|procedural]], [[stack-oriented programming language|stack-oriented]] and [[Reflection (computer science)|reflective]] programming language without [[Type system|type checking]], Forth features both interactive execution of commands (making it suitable as a [[operating system shell|shell]] for systems that lack a more formal [[operating system]]) and the ability to [[Compiler|compile]] sequences of commands for later execution. Some Forth implementations (usually early versions or those written to be extremely portable) compile [[threaded code]], but many implementations today generate [[compiler optimization|optimized]] [[machine language|machine code]] like other language compilers.
==Overview==
A Forth environment combines the compiler with an interactive shell. The user interactively defines and runs [[subroutine]]s, or "words," in a [[virtual machine]] similar to the [[runtime]] environment. Words can be tested, redefined, and debugged as the source is entered without recompiling or restarting the whole program. All syntactic elements, including variables and basic operators, appear as such procedures. Even if a particular word is optimized so as not to require a subroutine call, it is also still available as a subroutine. On the other hand, the shell may compile interactively typed commands into machine code before running them. (This behavior is common, but not required.) Forth environments vary in how the resulting program is stored, but ideally running the program has the same effect as manually re-entering the source. This contrasts with the combination of [[C (programming language)|C]] with [[Unix shell]]s, wherein compiled functions are a special class of program objects and interactive commands are strictly [[interpreter (computing)|interpreted]]. Most of Forth's unique properties result from this principle. As a "[[jack of all trades]]" including interaction, scripting, and compilation, Forth was popular on computers with limited resources, such as the [[BBC Micro]] and [[Apple II]] series, and remains so in applications such as [[firmware]] and small [[microcontroller]]s. Forth is broadly comparable to [[BASIC]], but emphasizing optimization over ease of use. Where C compilers may now generate code with more compactness and performance, Forth retains the advantage of interactivity.
Certain words are predefined, including the basic [[arithmetic]] operators. Predefined words which may be used at runtime are collectively called the "kernel." When the user starts an interactive Forth environment, it typically consists of the kernel and the interpreter. The compiler comprises a set of commands within the interpreter. Most of the ANS Forth standard is devoted to defining the contents of the kernel and the interface to the compiler. Aside from the predefined words, the main requirement is that words are executed in sequence. Here is an example of a programmer "developing" the [[hello world program]]. By convention, source code examples are written as a log, showing the programmer's input and the interpreter's response. Interpreters traditionally say "OK" after the successful completion of a command line.
0 > .( Hello, world!)
Hello, world! ok
0 > : hello_world ." Hello, world!" ;
ok
0 > hello_world
Hello, world! ok
In the first line, the text output operator <code>.(</code> is used interactively to immediately produce the output <code>Hello, world!</code>. The space after the <code>(</code> lets the interpreter parse the operator as a separate word and the <code>)</code> signals the end of the string. Next, the colon (<code>:</code>) is used to activate the compiler and store the same code, including the [[string (computer science)|string]] itself, into the word <code>hello_world</code>. Finally, the programmer activates the newly defined word to verify that it produces the expected output. Many Forth systems would allow <code>."</code> to be used in place of <code>.(</code> for consistency.
=== The stacks ===
Every programming environment with [[subroutine]]s implements a [[call stack]] for [[control flow]]. This structure typically also stores [[local variable]]s, including subroutine [[parameter (computer science)|parameter]]s (in a [[call by value]] system such as C). Forth often does not have local variables, however, nor is it call-by-value. Instead, intermediate values are kept in a second [[stack (data structure)|stack]]. Words operate directly on the topmost values in this stack. It may therefore be called the "parameter" or "data" stack, but most often simply "the" stack. The function-call stack is then called the "linkage" or "return" stack, abbreviated ''rstack''. Special rstack manipulation functions provided by the kernel allow it to be used for temporary storage within a word, but otherwise it cannot be used to pass parameters or manipulate data.
Most words are specified in terms of their effect on the stack. Typically, parameters are placed on the top of the stack before the word executes. After execution, the parameters have been erased and replaced with any return values. For arithmetic operators, this follows the rule of [[reverse Polish notation]]. See below for examples illustrating stack usage.
=== Maintenance ===
Forth is a simple yet extensible language; its modularity and extensibility permit the writing of high-level programs such as [[Computer-aided design|CAD]] systems. However, extensibility also helps poor programmers to write incomprehensible code, which has given Forth a reputation as a "[[write-only language]]". Forth has been used successfully in large, complex projects, while applications developed by competent, disciplined professionals have proven to be easily maintained on evolving hardware platforms over decades of use.<ref>{{cite web
| last =
| first =
| authorlink =
| coauthors =
| date =
| year =
| month =
| url = http://www.forth.org/successes.html
| title = Forth Success Stories
| format =
| work =
| pages =
| publisher =
| language =
| accessdate = 2006-06-09}}</ref>
Forth has a niche both in astronomical and space applications.<ref>{{cite web
| last =
| first =
| authorlink =
| coauthors =
| date =
| year =
| month =
| url = http://forth.gsfc.nasa.gov/
| title = Space Related Applications of Forth
| format =
| work =
| pages =
| publisher =
| language =
| accessdate = 2007-09-04}}</ref>
Forth is still used today in many [[embedded system]]s (small computerized devices) because of its [[porting|portability]], efficient memory use, short development time, and fast execution speed. It has been implemented efficiently on modern [[RISC processor]]s, and [[stack machine|processors that use Forth as machine language]] have been produced.<ref>{{cite web
| last =
| first =
| authorlink =
| coauthors =
| date =
| year =
| month =
| url = http://www.ultratechnology.com/
| title = Forth Chips Page
| format =
| work =
| pages =
| publisher =
| language = English
| accessdate = 2006-06-09
}}</ref> Other uses of Forth include the [[Open Firmware]] [[booting|boot ROMs]] used by [[Apple Inc.|Apple]], [[IBM]], [[Sun Microsystems|Sun]], and [[OLPC XO-1]]; and the [http://ficl.sourceforge.net/ FICL]-based [[BTX (boot loader)|first stage boot controller]] of the [[FreeBSD]] operating system.
==History==
Forth is so named because in 1968 "[t]he file holding the interpreter was labeled FORTH, for 4th (next) generation software — but the [[IBM 1130]] operating system restricted file names to 5 characters."<ref>{{ cite web | last = Moore | first = Charles H | year = 1991 | url = http://www.colorforth.com/HOPL.html | title = Forth - The Early Years | format = HTML | language = English | accessdate = 2006-06-03 }}</ref> Moore saw Forth as a successor to compile-link-go [[third-generation programming language]]s, or software for "fourth generation" hardware, not a [[fourth-generation programming language]] as the term has come to be used.
Forth evolved from [[Charles H. Moore]]'s personal programming system, which had been in continuous development since 1958.<ref name="evolution">{{cite web | url=http://www.forth.com/resources/evolution/index.html | title=The Evolution of Forth | coauthors=C. H. Moore, E. D. Rather, and D. R. Colburn | publisher=ACM SIGPLAN History of Programming Languages Conference | month=April | year=1993 | work=ACM SIGPLAN Notices, Volume 28, No. 3. March, 1993}}</ref> Forth was first exposed to other programmers in the early 1970s, starting with [[Elizabeth Rather]] at the US [[National Radio Astronomy Observatory]].<ref name="evolution"/> After their work at NRAO, Charles Moore and Elizabeth Rather formed FORTH, Inc. in 1973, refining and porting Forth systems to dozens of other platforms in the next decade.
Because Charles Moore had frequently moved from job to job over his career, an early pressure on the developing language was ease of [[porting]] to different computer architectures. A Forth system has often been used to bring up new hardware. For example, Forth was the first resident software on the new [[8086]] chip in 1978 and MacFORTH was the first resident development system for the first Apple [[Macintosh]] in 1984.<ref name="evolution"/>
FORTH, Inc's microFORTH was developed for the [[8080]], [[6800]], and [[Z80]] microprocessors starting in 1976. MicroFORTH was later used by hobbyists to generate Forth systems for other architectures, such as the [[6502]] in 1978. Wide dissemination finally led to standardization of the language. Common practice was codified in the de facto standards FORTH-79<ref>{{cite web | url=http://www.dartmouth.edu/~lmaurer/forth/Forth-79.pdf | title=The Forth-79 Standard}}</ref> and FORTH-83<ref>{{cite web | url=http://forth.sourceforge.net/standard/fst83/ | title=The Forth-83 Standard}}</ref> in the years 1979 and 1983, respectively. These standards were unified by [[American National Standards Institute|ANSI]] in 1994, commonly referred to as '''ANS Forth'''.<ref>{{ cite web | publisher = ANSI technical committee X3J14 | date = [[24 March]] [[1994]] | url = http://www.taygeta.com/forth/dpans.html | title = Programming Languages: Forth | format = HTML | language = English | accessdate = 2006-06-03 }}</ref>
Forth became very popular in the 1980s<ref>{{Harvard reference | Surname= | Given= | Authorlink= | Title=The Forth Language | Journal=BYTE Magazine | Volume=5 | Issue=8 | Year=1980 | Page= }}</ref> because it was well suited to the small [[microcomputer]]s of that time, as it is compact and portable. At least one [[home computer]], the British [[Jupiter Ace|Jupiter ACE]], had Forth in its [[Read-only memory|ROM]]-resident operating system. Rockwell also produced single-chip microcomputers with resident Forth kernels, the R65F11 and R65F12.
==Programmer's perspective==
{{further|[[Reverse Polish notation]]}}
Forth relies heavily on explicit use of a [[stack data structure|data stack]] and [[reverse Polish notation]] (RPN or postfix notation), commonly used in calculators from [[Hewlett-Packard]]. In RPN, the operator is placed after its operands, as opposed to the more common [[infix notation]] where the operator is placed between its operands. Postfix notation makes the language easier to parse and extend; Forth does not use a [[Backus-Naur form|BNF]] grammar, and does not have a monolithic compiler. Extending the compiler only requires writing a new word, instead of modifying a grammar and changing the underlying implementation.
Using RPN, one could get the result of the mathematical expression <code>(25 * 10 + 50)</code> this way:
25 10 * 50 + .
300 ok
[[Image:Stack1.svg|150px|left]]
This command line first puts the numbers 25 and 10 on the implied stack.{{clr}}
[[Image:Forthstack1 5.png|150px|left]]
<br>The word <code>*</code> multiplies the two numbers on the top of the stack and replaces them with their product.{{clr}}
[[Image:Forthstack2.PNG|150px|left]]
Then the number 50 is placed on the stack.{{clr}}
[[Image:Forthstack3.PNG|150px|left]]
<br>The word <code>+</code> adds it to the previous product. Finally, the <code>.</code> command prints the result to the user's terminal.<ref>{{cite book | last = Brodie | first = Leo | title = Starting Forth | format = paperback | edition = Second | year = 1987 | publisher = Prentice-Hall | language = English | id = ISBN 0-13-843079-9 | pages = 20}}</ref>{{clr}}
Even Forth's structural features are stack-based. For example:
: FLOOR5 ( n -- n' ) DUP 6 < IF DROP 5 ELSE 1 - THEN ;
This code defines a new word (again, 'word' is the term used for a subroutine) called <code>FLOOR5</code> using the following commands: <code>DUP</code> duplicates the number on the stack; <code><</code> compares 6 with the top number on the stack and replaces it with a true-or-false value; <code>IF</code> takes a true-or-false value and chooses to execute commands immediately after it or to skip to the <code>ELSE</code>; <code>DROP</code> discards the value on the stack; and <code>THEN</code> ends the conditional. The text in parentheses is a comment, advising that this word expects a number on the stack and will return a possibly changed number. The net result performs similarly to this function written in the [[C (programming language)|C programming language]]:
int floor5(int v) { return v < 6 ? 5 : v - 1; }
This function is written more succinctly as:
: FLOOR5 ( n -- n' ) 1- 5 MAX ;
== Facilities==
Forth [[parsing]] is simple, as it has no explicit [[grammar]]. The interpreter reads a line of input from the user input device, which is then parsed for a word using spaces as a [[delimiter]]; some systems recognise additional [[whitespace]] characters. When the interpreter finds a word, it tries to look the word up in the ''dictionary''. If the word is found, the interpreter executes the code associated with the word, and then returns to parse the rest of the input stream. If the word isn't found, the word is assumed to be a number, and an attempt is made to convert it into a number and push it on the stack; if successful, the interpreter continues parsing the input stream. Otherwise, if both the lookup and number conversion fails, the interpreter prints the word followed by an error message indicating the word is not recognised, flushes the input stream, and waits for new user input.<ref>{{ cite book | last = Brodie | first = Leo | title = Starting Forth | format = paperback | edition = Second | year = 1987 | publisher = Prentice-Hall | language = English | id = ISBN 0-13-843079-9 | pages = 14 }}</ref>
The definition of a new word is started with the word <code>:</code> (colon) and ends with the word <code>;</code> (semi-colon). For example
: X DUP 1+ . . ;
will compile the word <code>X</code>, and makes the name findable in the dictionary. When executed by typing <code>10 X</code> at the console this will print <code>11 10</code>.<ref name="compiler">{{ cite book | last = Brodie | first = Leo | title = Starting Forth | format = paperback | edition = Second | year = 1987 | publisher = Prentice-Hall | language = English | id = ISBN 0-13-843079-9 | pages = 16 }}</ref>
Most Forth systems include a specialized [[Assembly_language#Assembler|assembler]] that produces executable words. The assembler is a special dialect of the compiler. Forth assemblers often use a reverse-polish syntax in which the parameters of an instruction precede the instruction. The usual design of a Forth assembler is to construct the instruction on the stack, then copy it into memory as the last step. Registers may be referenced by the name used by the manufacturer, numbered (0..n, as used in the actual operation code) or named for their purpose in the Forth system: e.g. "S" for the register used as a stack pointer.<ref>{{ cite web | last = Rodriguez | first = Brad | url = http://www.zetetics.com/bj/papers/6809asm.txt | title = B.Y.O.ASSEMBLER | format = HTML | language = English | accessdate = 2006-06-19 }}</ref>
=== Operating system, files and multitasking ===
Classic Forth systems traditionally use neither [[operating system]] nor [[file system]]. Instead of storing code in files, source-code is stored in disk blocks written to physical disk addresses. The word <code>BLOCK</code> is employed to translate the number of a 1K-sized block of disk space into the address of a buffer containing the data, which is managed automatically by the Forth system. Some implement contiguous disk files using the system's disk access, where the files are located at fixed disk block ranges. Usually these are implemented as fixed-length binary records, with an integer number of records per disk block. Quick searching is achieved by hashed access on key data.
[[computer multitasking|Multitasking]], most commonly [[Computer_multitasking#Cooperative_multitasking/time-sharing|cooperative]] [[round-robin scheduling]], is normally available (although multitasking words and support are not covered by the ANSI Forth Standard). The word <code>PAUSE</code> is used to save the current task's execution context, to locate the next task, and restore its execution context. Each task has its own stacks, private copies of some control variables and a scratch area. Swapping tasks is simple and efficient; as a result, Forth multitaskers are available even on very simple [[microcontroller]]s such as the [[Intel 8051]], [[Atmel AVR]], and [[TI MSP430]].<ref>{{ cite web | last = Rodriguez | first = Brad | url = http://www.zetetics.com/bj/papers/8051task.pdf | title = MULTITASKING 8051 CAMELFORTH | format = PDF | language = English | accessdate = 2006-06-19 }}</ref>
By contrast, some Forth systems run under a host operating system such as [[Microsoft Windows]], [[Linux]] or a version of [[Unix]] and use the host operating system's file system for source and data files; the ANSI Forth Standard describes the words used for I/O. Other non-standard facilities include a mechanism for issuing [[system call|call]]s to the host OS or [[windowing system]]s, and many provide extensions that employ the scheduling provided by the operating system. Typically they have a larger and different set of words from the stand-alone Forth's <code>PAUSE</code> word for task creation, suspension, destruction and modification of priority.
=== Self compilation and cross compilation ===
A full-featured Forth system with all source code will compile itself, a technique commonly called meta-compilation by Forth programmers (although the term doesn't exactly match [[Meta-Compilation|meta-compilation]] as it is normally defined). The usual method is to redefine the handful of words that place compiled bits into memory. The compiler's words use specially-named versions of fetch and store that can be redirected to a buffer area in memory. The buffer area simulates or accesses a memory area beginning at a different address than the code buffer. Such compilers define words to access both the target computer's memory, and the host (compiling) computer's memory.<ref>{{ cite web | last = Rodriguez | first = Brad | year = 1995 | month = July | url = http://www.zetetics.com/bj/papers/moving8.htm | title = MOVING FORTH | format = HTML | language = English | accessdate = 2006-06-19 }}</ref>
After the fetch and store operations are redefined for the code space, the compiler, assembler, etc. are recompiled using the new definitions of fetch and store. This effectively reuses all the code of the compiler and interpreter. Then, the Forth system's code is compiled, but this version is stored in the buffer. The buffer in memory is written to disk, and ways are provided to load it temporarily into memory for testing. When the new version appears to work, it is written over the previous version.
There are numerous variations of such compilers for different environments. For [[embedded system]]s, the code may instead be written to another computer, a technique known as [[Cross-compilation|cross compilation]], over a serial port or even a single [[Transistor-transistor logic|TTL]] bit, while keeping the word names and other non-executing parts of the dictionary in the original compiling computer. The minimum definitions for such a forth compiler are the words that fetch and store a byte, and the word that commands a Forth word to be executed. Often the most time-consuming part of writing a remote port is constructing the initial program to implement fetch, store and execute, but many modern microprocessors have integrated debugging features (such as the [[Motorola CPU32]]) that eliminate this task.<ref>{{ cite web | last = Shoebridge | first = Peter | date = [[1998-12-21]] | url = http://www.zeecube.com/archive/bdm/index.htm | title = Motorola Background Debugging Mode Driver for Windows NT | format = HTML | language = English | accessdate = 2006-06-19 }}</ref>
== Structure of the language ==
The basic data structure of Forth is the "dictionary" which maps "words" to executable code or named data structures. The dictionary is laid out in memory as a [[linked list]] with the links proceeding from the latest (most recently) defined word to oldest, until a sentinel, usually a NULL pointer, is found.
A defined word generally consists of ''head'' and ''body'' with the head consisting of the ''name field'' (NF) and the ''link field'' (LF) and body consisting of the ''code field'' (CF) and the ''parameter field'' (PF).
Head and body of a dictionary entry are treated separately because they may not be contiguous. For example, when a Forth program is recompiled for a new platform, the head may remain on the compiling computer, while the body goes to the new platform. In some environments (such as [[embedded system]]s) the heads occupy memory unnecessarily. However, some cross-compilers may put heads in the target if the target itself is expected to support an interactive Forth.<ref>{{cite web
| last = Martin
| first = Harold M.
| authorlink =
| coauthors =
| date =
| year = 1991
| month = March
| url = http://portal.acm.org/citation.cfm?id=122089.122091&coll=portal&dl=ACM&idx=J696&part=periodical&WantType=periodical&title=ACM%20SIGFORTH%20Newsletter
| title = Developing a tethered Forth model
| format =
| work =
| pages =
| publisher = ACM Press
| language = English
| accessdate = 2006-06-19
}}</ref>
===Dictionary entry===
The exact format of a dictionary entry is not prescribed, and implementations vary. However, certain components are almost always present, though the exact size and order may vary. Described as a structure, a dictionary entry might look this way:<ref>{{cite book
| last = Brodie
| first = Leo
| authorlink =
| coauthors =
| editor =
| others =
| title = Starting Forth
| origdate =
| origyear =
| origmonth =
| url =
| format = paperback
| accessdate =
| accessyear =
| accessmonth =
| edition = Second
| date =
| year = 1987
| month =
| publisher = Prentice-Hall
| location =
| language = English
| id = ISBN 0-13-843079-9
| doi =
| pages = 200-202
| chapter =
| chapterurl =
| quote =
}}</ref>
structure
byte: flag \ 3bit flags + length of word's name
char-array: name \ name's runtime length isn't known at compile time
address: previous \ link field, backward ptr to previous word
address: codeword \ ptr to the code to execute this word
any-array: parameterfield \ unknown length of data, words, or opcodes
end-structure forthword
The name field starts with a prefix giving the length of the word's name (typically up to 32 bytes), and several bits for flags. The character representation of the word's name then follows the prefix. Depending on the particular implementation of Forth, there may be one or more NUL ('\0') bytes for alignment.
The link field contains a pointer to the previously defined word. The pointer may be a relative displacement or an absolute address that points to the next oldest sibling.
The code field pointer will be either the address of the word which will execute the code or data in the parameter field or the beginning of machine code that the processor will execute directly. For colon defined words, the code field pointer points to the word that will save the current Forth instruction pointer (IP) on the return stack, and load the IP with the new address from which to continue execution of words. This is the same as what a processor's call/return instructions does.
===Structure of the compiler===
The compiler itself consists of Forth words visible to the system, not a monolithic program. This allows a programmer to change the compiler's words for special purposes.
The "compile time" flag in the name field is set for words with "compile time" behavior. Most simple words execute the same code whether they are typed on a command line, or embedded in code. When compiling these, the compiler simply places code or a threaded pointer to the word.<ref name="compiler"/>
The classic examples of compile-time words are the [[control structure]]s such as <code>IF</code> and <code>WHILE</code>. All of Forth's control structures, and almost all of its compiler are implemented as compile-time words. All of Forth's [[control flow]] words are executed during compilation to compile various combinations of the primitive words <code>BRANCH</code> and <code>?BRANCH</code> (branch if false). During compilation, the data stack is used to support control structure balancing, nesting, and backpatching of branch addresses. The snippet:
... DUP 6 < IF DROP 5 ELSE 1 - THEN ...
would be compiled to the following sequence inside of a definition:
... DUP LIT 6 < ?BRANCH 5 DROP LIT 5 BRANCH 3 LIT 1 - ...
The numbers after <code>BRANCH</code> represent relative jump addresses. <code>LIT</code> is the primitive word for pushing a "literal" number onto the data stack.
==== Compilation state and interpretation state ====
The word <code>:</code> (colon) parses a name as a parameter, creates a dictionary entry (a ''colon definition'') and enters compilation state. The interpreter continues to read space-delimited words from the user input device. If a word is found, the interpreter executes the ''compilation semantics'' associated with the word, instead of the ''interpretation semantics''. The default compilation semantics of a word are to append its interpretation semantics to the current definition.<ref name="compiler"/>
The word <code>;</code> (semi-colon) finishes the current definition and returns to interpretation state. It is an example of a word whose compilation semantics differ from the default. The interpretation semantics of <code>;</code> (semi-colon), most control flow words, and several other words are undefined in ANS Forth, meaning that they must only be used inside of definitions and not on the interactive command line.<ref name="compiler"/>
The interpreter state can be changed manually with the words <code><nowiki>[</nowiki></code> (left-bracket) and <code><nowiki>]</nowiki></code> (right-bracket) which enter interpretation state or compilation state, respectively. These words can be used with the word <code>LITERAL</code> to calculate a value during a compilation and to insert the calculated value into the current colon definition. <code>LITERAL</code> has the compilation semantics to take an object from the data stack and to append semantics to the current colon definition to place that object on the data stack.
In ANS <!-- not a misspelling --> Forth, the current state of the interpreter can be read from the [[flag (computing)|flag]] <code>STATE</code> which contains the value true when in compilation state and false otherwise. This allows the implementation of so-called ''state-smart words'' with behavior that changes according to the current state of the interpreter.
==== Immediate words ====
The word <code>IMMEDIATE</code> marks the most recent colon definition as an ''immediate word'', effectively replacing its compilation semantics with its interpretation semantics.<ref>{{cite book
| last = Brodie
| first = Leo
| authorlink =
| coauthors =
| editor =
| others =
| title = Starting Forth
| origdate =
| origyear =
| origmonth =
| url =
| format = paperback
| accessdate =
| accessyear =
| accessmonth =
| edition = Second
| date =
| year = 1987
| month =
| publisher = Prentice-Hall
| location =
| language = English
| id = ISBN 0-13-843079-9
| doi =
| pages = 273
| chapter =
| chapterurl =
| quote =
}}</ref> Immediate words are always executed, not compiled, in either state. <code>;</code> is an example of an immediate word. In ANS Forth, the word <code>POSTPONE</code> takes a name as a parameter and appends the compilation semantics of the named word to the current definition even if the word was marked immediate. Forth-83 defined separate words <code>COMPILE</code> and <code>[COMPILE]</code> to force the compilation of non-immediate and immediate words, respectively.
==== Unnamed words and execution tokens ====
In ANS Forth, unnamed words can be defined with the word <code>:NONAME</code> which compiles the following words up to the next <code>;</code> (semi-colon) and leaves an ''execution token'' on the data stack. The execution token provides an opaque handle for the compiled semantics, similar to the [[function pointer]]s of the [[C (programming language)|C programming language]].
Execution tokens can be stored in variables. The word <code>EXECUTE</code> takes an execution token from the data stack and performs the associated semantics. The word <code>COMPILE,</code> (compile-comma) takes an execution token from the data stack and appends the associated semantics to the current definition.
The word <code><nowiki>'</nowiki></code> (tick) takes the name of a word as a parameter and returns the execution token associated with that word on the data stack. In interpretation state, <code>' RANDOM-WORD EXECUTE</code> is equivalent to <code>RANDOM-WORD</code>.<ref>{{cite book
| last = Brodie
| first = Leo
| authorlink =
| coauthors =
| editor =
| others =
| title = Starting Forth
| origdate =
| origyear =
| origmonth =
| url =
| format = paperback
| accessdate =
| accessyear =
| accessmonth =
| edition = Second
| date =
| year = 1987
| month =
| publisher = Prentice-Hall
| location =
| language = English
| id = ISBN 0-13-843079-9
| doi =
| pages = 199
| chapter =
| chapterurl =
| quote =
}}</ref>
==== Parsing words and comments ====
The words <code>:</code> (colon), <code>POSTPONE</code>, <code><nowiki>'</nowiki></code> (tick) and <code>:NONAME</code> are examples of ''parsing words'' that take their arguments from the user input device instead of the data stack. Another example is the word <code>(</code> (paren) which reads and ignores the following words up to and including the next right parenthesis and is used to place comments in a colon definition. Similarly, the word <code>\</code> (backslash) is used for comments that continue to the end of the current line. To be parsed correctly, <code>(</code> (paren) and <code>\</code> (backslash) must be separated by whitespace from the following comment text.
<!-- TO DO: Explain PARSE and FIND. -->
===Structure of code===
In most Forth systems, the body of a code definition consists of either [[machine language]], or some form of [[threaded code]]. Traditionally, indirect-threaded code was used, but direct-threaded and subroutine threaded Forths have also been popular. The fastest modern Forths use subroutine threading, insert simple words as macros, and perform [[peephole optimization]] or other optimizing strategies to make the code smaller and faster.<ref>{{cite web
| last = Ertl
| first = M. Anton
| authorlink =
| coauthors = Gregg, David
| date =
| year =
| month =
| url = http://dec.bournemouth.ac.uk/forth/euro/ef03/ertl-gregg03.pdf
| title = Implementation Issues for Superinstructions in Gforth
| format = PDF
| work =
| pages =
| publisher =
| language = English
| accessdate = 2006-06-19
}}</ref>
===Data objects===
When a word is a variable or other data object, the CF points to the runtime code associated with the defining word that created it. A defining word has a characteristic "defining behavior" (creating a dictionary entry plus possibly allocating and initializing data space) and also specifies the behavior of an instance of the class of words constructed by this defining word. Examples include:
;<code>VARIABLE</code>
:Names an uninitialized, one-cell memory location. Instance behavior of a <code>VARIABLE</code> returns its address on the stack.
;<code>CONSTANT</code>
:Names a value (specified as an argument to <code>CONSTANT</code>). Instance behavior returns the value.
;<code>CREATE</code>
:Names a location; space may be allocated at this location, or it can be set to contain a string or other initialized value. Instance behavior returns the address of the beginning of this space.
Forth also provides a facility by which a programmer can define new application-specific defining words, specifying both a custom defining behavior and instance behavior. Some examples include circular buffers, named bits on an I/O port, and automatically-indexed arrays.
Data objects defined by these and similar words are global in scope. The function provided by local variables in other languages is provided by the data stack in Forth (although Forth also has real local variables). Forth programming style uses very few named data objects compared with other languages; typically such data objects are used to contain data which is used by a number of words or tasks (in a multitasked implementation).<ref>{{cite book
| last = Brodie
| first = Leo
| authorlink =
| coauthors =
| editor =
| others =
| title = Starting Forth
| origdate =
| origyear =
| origmonth =
| url =
| format = paperback
| accessdate =
| accessyear =
| accessmonth =
| edition = 2nd
| date =
| year = 1987
| month =
| publisher = Prentice-Hall
| location =
| language =
| id = ISBN 0-13-843079-9
| doi =
| pages = 241
| chapter = Under The Hood
| chapterurl =
| quote = To summarize, there are three kinds of variables: System variables contain values used by the entire Forth system. User variables contain values that are unique for each task, even though the definitions can be used by all tasks in the system. Regular variables can be accessible either system-wide or within a single task only, depending upon whether they are defined within <code>OPERATOR</code> or within a private task.
}}</ref>
Forth does not enforce consistency of data type usage; it is the programmer's responsibility to use appropriate operators to fetch and store values or perform other operations on data.
==Programming==
Words written in Forth are compiled into an executable form. The classical "indirect threaded" implementations compile lists of addresses of words to be executed in turn; many modern systems generate actual machine code (including calls to some external words and code for others expanded in place). Some systems have optimizing compilers. Generally speaking, a Forth program is saved as the memory image of the compiled program with a single command (e.g., RUN) that is executed when the compiled version is loaded.
During development, the programmer uses the interpreter to execute and test each little piece as it is developed. Most Forth programmers therefore advocate a loose top-down design, and bottom-up development with continuous testing and integration.<ref>{{cite book
| last = Brodie
| first = Leo
| authorlink =
| coauthors =
| editor =
| others =
| title = Thinking Forth
| origdate =
| origyear =
| origmonth =
| url =
| format = paperback
| accessdate =
| accessyear =
| accessmonth =
| edition =
| date =
| year = 1984
| month =
| publisher = Prentice-Hall
| location =
| language =
| id = ISBN 0-13-917568-7
| doi =
| pages =
| chapter =
| chapterurl =
| quote =
}}</ref>
The top-down design is usually separation of the program into "vocabularies" that are then used as high-level sets of tools to write the final program. A well-designed Forth program reads like natural language, and implements not just a single solution, but also sets of tools to attack related problems.
==Code examples==
===Hello world===
''For an explanation of the tradition of programming "Hello World", see [[Hello world program]].''
One possible implementation:
: HELLO ( -- ) CR ." Hello, world!" ;
HELLO
The word <code>CR</code> causes the following output to be displayed on a new line. The parsing word <code>."</code> (dot-quote) reads a double-quote delimited string and appends code to the current definition so that the parsed string will be displayed on execution. The space character separating the word <code>."</code> from the string <code>Hello, world!</code> is not included as part of the string. It is needed so that the parser recognizes <code>."</code> as a Forth word.
A standard Forth system is also an interpreter, and the same output can be obtained by typing the following code fragment into the Forth console:
CR .( Hello, world!)
<code>.(</code> (dot-paren) is an immediate word that parses a parenthesis-delimited string and displays it. As with the word <code>."</code> the space character separating <code>.(</code> from <code>Hello, world!</code> is not part of the string.
The word <code>CR</code> comes before the text to print. By convention, the Forth interpreter does not start output on a new line. Also by convention, the interpreter waits for input at the end of the previous line, after an <code>ok</code> prompt. There is no implied 'flush-buffer' action in Forth's <code>CR</code>, as sometimes is in other programming languages.
=== Mixing compilation state and interpretation state ===
Here is the definition of a word <code>EMIT-Q</code> which when executed emits the single character <code>Q</code>:
: EMIT-Q 81 ( the ASCII value for the character 'Q' ) EMIT ;
This definition was written to use the [[ASCII]] value of the <code>Q</code> character (81) directly. The text between the parentheses is a comment and is ignored by the compiler. The word <code>EMIT</code> takes a value from the data stack and displays the corresponding character.
The following redefinition of <code>EMIT-Q</code> uses the words <code><nowiki>[</nowiki></code> (left-bracket), <code><nowiki>]</nowiki></code> (right-bracket), <code>CHAR</code> and <code>LITERAL</code> to temporarily switch to interpreter state, calculate the ASCII value of the <code>Q</code> character, return to compilation state and append the calculated value to the current colon definition:
: EMIT-Q [ CHAR Q ] LITERAL EMIT ;
The parsing word <code>CHAR</code> takes a space-delimited word as parameter and places the value of its first character on the data stack. The word <code><nowiki>[CHAR]</nowiki></code> is an immediate version of <code>CHAR</code>. Using <code><nowiki>[CHAR]</nowiki></code>, the example definition for <code>EMIT-Q</code> could be rewritten like this:
: EMIT-Q [CHAR] Q EMIT ; \ Emit the single character 'Q'
This definition used <code>\</code> (backslash) for the describing comment.
Both <code>CHAR</code> and <code><nowiki>[CHAR]</nowiki></code> are predefined in ANS Forth. Using <code>IMMEDIATE</code> and <code>POSTPONE</code>, <code><nowiki>[CHAR]</nowiki></code> could have been defined like this:
: [CHAR] CHAR POSTPONE LITERAL ; IMMEDIATE
==Implementations==
Because the Forth virtual machine is simple to implement and has no standard reference implementation, there are a plethora of implementations of the language. In addition to supporting the standard varieties of desktop computer systems ([[POSIX]], [[Microsoft Windows]], [[Mac OS X]]), many of these Forth systems also target a variety of [[embedded systems]]. Listed here are the some of the more prominent systems which obey the 1994 ANS Forth standard.
* [http://www.complang.tuwien.ac.at/forth/gforth/ GNU Forth] - a portable ANS Forth implementation from the [[GNU Project]]
* [http://www.forth.com/ Forth Inc.] - founded by the originators of Forth, sells desktop (SwiftForth) and embedded (SwiftX) ANS Forth solutions
* [http://www.mpeforth.com/ MPE Ltd.] - sells highly-optimized desktop (VFX) and embedded ANS Forth compilers
* [[Open Firmware]] - a [[bootloader]] and [[BIOS]] standard based on ANS Forth
* [http://www.forth.org/compilers.html Freely available implementations]
* [http://www.forth.org/commercial.html Commercial implementations]
* A more up-to-date index of [http://wiki.forthfreak.net/index.cgi?ForthSystems Forth systems], organized by platform
== See also ==
* [[Canon Cat]]
* [[PostScript]]
* [[FCode]]
* [[colorForth]]
* [[MUF (programming language)]]
* [[Elizabeth Rather]]
* [[STOIC]]
* [[Joy (programming language)|Joy]]
* [[Jupiter ACE]]
* [[Factor (programming language)|Factor]]
== Notes ==
{{reflist|2}}
== References ==
{{refbegin|2}}
*{{cite book | last=Brodie | first=Leo | coauthors= | editor=Marcel Hendrix | others=Marlin Ouverson | title=Starting Forth | origdate= | origyear= | origmonth= | url=http://www.forth.com/starting-forth/index.html | format=Online book | accessdate= 2007-09-29 | accessyear= | accessmonth= | edition=Web edition | date= | year=2007| month= | publisher=FORTH, Inc. | location= | language=English | id= | pages= | chapter= | chapterurl= }}
*{{cite book | last=Brodie | first=Leo | coauthors= | editor=Bernd Paysan | others= | title=Thinking Forth | origdate= | origyear= | origmonth= | url=http://thinking-forth.sourceforge.net | format=PDF Online book | accessdate=2006-06-19 | accessyear= | accessmonth= | edition= | date= | year=2004 | month= | publisher= | location= | language=English | id=ISBN 0-9764587-0-5 | pages= | chapter= | chapterurl= }}
*{{cite book | last=Conklin | first=Edward K. | coauthors=Elizabeth D. Rather et al | editor= | others= | title=Forth Programmer's Handbook | origdate= | origyear= | origmonth= | url=http://www.forth.com/forth/forth-books.html | format=paperback | accessdate= | accessyear= | accessmonth= | edition=3rd | date=08 | year=2007 | month=09 | publisher=BookSurge Publishing | location= | language=English | id=ISBN 1-4196-7549-4| pages=274 | chapter= | chapterurl= }}
*{{cite book | last=Rather | first=Elizabeth D. | coauthors= | editor= | others= | title=Forth Application Techniques | origdate= | origyear= | origmonth= | url=http://www.forth.com/forth/forth-books.html | format=spiral bound | accessdate= | accessyear= | accessmonth= | edition= | date= | year= | month= | publisher=Forth Inc. | location= | language=English | id=ISBN 0-9662156-1-3 | pages=158 | chapter= | chapterurl= }}
*{{cite book | last=Pelc | first=Stephen F. | coauthors= | editor= | others= | title=Programming Forth | origdate= | origyear=2005 | origmonth= | url=http://www.mpeforth.com/books.htm | format=spiral bound | accessdate= | accessyear= | accessmonth= | edition= | date= | year= | month= | publisher=MicroProcessor Engineering Ltd | location= | language=English | pages=188 | chapter= | chapterurl= }}
*{{cite book | last=Kelly | first=Mahlon G. | coauthors=Nicholas Spies | editor= | others= | title=FORTH: A Text and Reference | origdate= | origyear= | origmonth= | url= | format= | accessdate= | accessyear= | accessmonth= | edition= | date= | year= | month= | publisher=Prentice-Hall | location= | language=English | id=ISBN 0-13-326331-2 | pages= | chapter= | chapterurl= }}
*{{cite book | last=Koopman, Jr | first=Philip J. | coauthors= | editor= | others= | title=Stack Computers: The New Wave | origdate= | origyear= | origmonth= | url=http://www.ece.cmu.edu/~koopman/stack_computers/index.html | format=hardcover | accessdate= | accessyear= | accessmonth= | edition= | date= | year=1989 | month= | publisher=Ellis Horwood Limited | location= | language=English | id=ISBN 0-7458-0418-7 | pages= | chapter= | chapterurl= }}
* {{ cite book | last = Pountain | first = Dick | title = Object-oriented Forth: Implementation of Data Structures | format = paperback | year = 1987 | publisher = Harcourt Brace Jovanovich | language = English | id = ISBN 0-12-563570-2 }}
* {{ cite book | last = Payne | first = William | title = Embedded Controller Forth for the 8051 Family | date = [[19 December]] [[1990]] | publisher = Elsevier | language = English | id = ISBN 978-0125475709 | pages = 528 }}
{{refend}}
== External links ==
{{wikibooks|Forth}}
* [news://comp.lang.forth comp.lang.forth] - [[Usenet]] newsgroup with active Forth discussion
* [http://www.complang.tuwien.ac.at/forth/threading/ Execution speed of threading]
* [http://www.ultratechnology.com/ Forth Chips Page] — Forth in hardware
* [http://www.dataman.ro/dforth Delta Forth .NET] a Forth compiler for the [[.NET Framework|.NET]] Platform
* [http://galileo.phys.virginia.edu/classes/551.jvn.fall01/primer.htm A Beginner's Guide to Forth] by J.V. Noble
* [http://forthlinks.com Forth Links]
* [http://dmoz.org/Computers/Programming/Languages/Forth/ Computers/Programming/Languages/Forth] at the Open Directory Project
* [http://www.complang.tuwien.ac.at/forth/family-tree/ Forth family tree and timeline]
* [http://dobbscodetalk.com/index.php?option=com_myblog&show=In-this-1980-article-from-Byte-Charles-Moore-recounts-the-creation-of-Forth..html&Itemid=29 The Evolution of FORTH, an Unusual Language] by Charles H. Moore
* [http://www.bluishcoder.co.nz/2008/05/extending-tamarin-tracing-with-forth.html Extending Tamarin Tracing with Forth] - blog post by [[Chris Double]], Mozilla developer
* [http://www.techworld.com.au/article/250530/-z_programming_languages_forth Computerworld Interview with Charles H. Moore on Forth]
* [http://forth.gsfc.nasa.gov/ NASA applications of Forth]
[[Category:.NET programming languages]]
[[Category:Concatenative programming languages]]
[[Category:Forth programming language family]]
[[bg:Forth]]
[[cs:Forth]]
[[de:Forth (Informatik)]]
[[es:Forth]]
[[fr:Forth (langage)]]
[[gl:Forth]]
[[ko:포스 (프로그래밍 언어)]]
[[it:Forth]]
[[nl:Forth (programmeertaal)]]
[[ja:Forth]]
[[no:Forth (programmeringsspråk)]]
[[pl:Forth]]
[[pt:Forth]]
[[ru:Forth (язык программирования)]]
[[fi:Forth]]
[[sv:Forth (programspråk)]]
[[uk:Forth]]
[[zh:Forth]]