Forth (programming language)
Forth is a stack-oriented programming language and interactive integrated development environment designed by Charles H. "Chuck" Moore and first used by other programmers in 1970. Although not an acronym, the language's name in its early years was often spelled in all capital letters as FORTH. The FORTH-79 and FORTH-83 implementations, which were not written by Moore, became de facto standards, and an official technical standard of the language was published in 1994 as ANS Forth. A wide range of Forth derivatives existed before and after ANS Forth. The free and open-source software Gforth implementation is actively maintained, as are several commercially supported systems. Forth typically combines a compiler with an integrated command shell,[a] where the user interacts via subroutines called words. Words can be defined, tested, redefined, and debugged without recompiling or restarting the whole program. All syntactic elements, including variables, operators, and control flow, are defined as words. A stack is used to pass parameters between words, leading to a Reverse Polish notation style. For much of Forth's existence, the standard technique was to compile to threaded code, which can be interpreted faster than bytecode. One of the early benefits of Forth was size: an entire development environment—including compiler, editor, and user programs—could fit in memory on an 8-bit or similarly limited system. No longer constrained by space, there are modern implementations that generate optimized machine code like other language compilers. The relative simplicity of creating a basic Forth system has led to many personal and proprietary variants, such as the custom Forth used to implement the bestselling 1986 video game Starflight from Electronic Arts.[1] Forth is used in the Open Firmware boot loader, in spaceflight applications[2] such as the Philae spacecraft,[3][4] and in other embedded systems which involve interaction with hardware. Moore developed a series of microprocessors for executing compiled Forth-like code directly and experimented with smaller languages based on Forth concepts, including cmForth and colorForth. Most of these languages were designed to support Moore's own projects, such as chip design. UsesForth has a niche in astronomical and space applications[5] as well as a history in embedded systems. The Open Firmware boot ROMs used by Apple, IBM, Sun, and OLPC XO-1 contain a Forth environment. Forth has often been used to bring up new hardware. Forth was the first resident software on the new Intel 8086 chip in 1978, and MacFORTH was the first resident development system for the Macintosh 128K in 1984.[6] Atari, Inc. used an elaborate animated demo written in Forth to showcase capabilities of the Atari 8-bit computers in department stores.[7] Electronic Arts published multiple video games in the 1980s that were written in Forth, including Worms? (1983),[8] Adventure Construction Set (1984),[9] Amnesia (1986),[10] Starflight (1986),[1] and Lords of Conquest (1986). Robot coding game ChipWits (1984) was written in MacFORTH.[11] Ashton-Tate's RapidFile (1986), a flat-file database program, and VP-Planner[12] from Paperback Software International (1983), a spreadsheet program competing with Lotus 1-2-3, were written in Forth. The Canon Cat (1987) uses Forth for its system programming. Rockwell produced single-chip microcomputers with resident Forth kernels: the R65F11 and R65F12. ASYST was a Forth expansion for measuring and controlling on PCs.[13] HistoryForth evolved from Charles H. Moore's personal programming system, which had been in continuous development since 1968.[6][14] Forth was first exposed to other programmers in the early 1970s, starting with Elizabeth Rather at the United States National Radio Astronomy Observatory (NRAO).[6] 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. Moore saw Forth as a successor to compile-link-go third-generation programming languages, or software for "fourth generation" hardware. He recalls how the name was coined:[15]
FORTH, Inc.'s microFORTH was developed for the Intel 8080, Motorola 6800, Zilog Z80, and RCA 1802 microprocessors, starting in 1976. MicroFORTH was later used by hobbyists to generate Forth systems for other architectures, such as the 6502 in 1978. The Forth Interest Group was formed in 1978.[16] It promoted and distributed its own version of the language, FIG-Forth, for most makes of home computer. Forth was popular in the early 1980s,[17] because it was well suited to the limited memory of microcomputers. The ease of implementing the language led to many implementations.[18] The Jupiter ACE home computer has Forth in its ROM-resident operating system. Insoft GraFORTH is a version of Forth with graphics extensions for the Apple II.[19] Common practice was codified in the de facto standards FORTH-79[20] and FORTH-83[21] in the years 1979 and 1983, respectively. These standards were unified by ANSI in 1994, commonly referred to as ANS Forth.[22][23] As of 2018, the source for the original 1130 version of FORTH has been recovered, and is now being updated to run on a restored or emulated 1130 system.[24] OverviewForth emphasizes the use of small, simple functions called words. Words for bigger tasks call upon many smaller words that each accomplish a distinct sub-task. A large Forth program is a hierarchy of words. These words, being distinct modules that communicate implicitly via a stack mechanism, can be prototyped, built and tested independently. The highest level of Forth code may resemble an English-language description of the application. Forth has been called a meta-application language: a language that can be used to create problem-oriented languages.[25] Forth relies on implicit use of a data stack and reverse Polish notation which is 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's flexibility makes a static BNF grammar inappropriate, and it 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 can compute the value of the arithmetic expression (25 × 10) + 50 in the following way: 25 10 * 50 + CR .
300 ok
![]() First the numbers 25 and 10 are put on the stack. ![]()
![]() Then the number 50 is placed on the stack. ![]()
Even Forth's structural features are stack-based. For example: : FLOOR5 ( n -- n' ) DUP 6 < IF DROP 5 ELSE 1 - THEN ;
The colon indicates the beginning of a new definition, in this case a new word (again, word is the term used for a subroutine) called The subroutine uses the following commands: The int floor5(int v) {
return (v < 6) ? 5 : (v - 1);
}
This function is written more succinctly as: : FLOOR5 ( n -- n' ) 1- 5 MAX ;
This can be run as follows: 1 FLOOR5 CR .
5 ok
8 FLOOR5 CR .
7 ok
First a number (1 or 8) is pushed onto the stack, FacilitiesForth's grammar has no official specification. Instead, it is defined by a simple algorithm. 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 looks 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 the number conversion fail, the interpreter prints the word followed by an error message indicating that the word is not recognised, flushes the input stream, and waits for new user input.[27] The definition of a new word is started with the word : X DUP 1+ . . ;
will compile the word Most Forth systems include an assembler to write words using the processor's facilities. Forth assemblers often use a reverse Polish syntax in which the parameters of an instruction precede the instruction. A typical reverse Polish assembler prepares the operands on the stack and the mnemonic copies the whole instruction into memory as the last step. A Forth assembler is by nature a macro assembler, so that it is easy to define an alias for registers according to their role in the Forth system: e.g. "dsp" for the register used as the data stack pointer.[29] Operating system, files, and multitaskingMost 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. All modern Forth systems use normal text files for source, even if they are embedded. An embedded system with a resident compiler gets its source via a serial line. 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 Multitasking, most commonly cooperative round-robin scheduling, is normally available (although multitasking words and support are not covered by the ANSI Forth Standard). The word Other non-standard facilities include a mechanism for issuing calls to the host OS or windowing systems, 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 Self-compilation and cross compilationA full-featured Forth system with all source code will compile itself, a technique commonly called meta-compilation or self-hosting, by Forth programmers (although the term doesn't exactly match 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.[31] 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. Numerous variations of such compilers exist for different environments. For embedded systems, the code may instead be written to another computer, a technique known as cross compilation, over a serial port or even a single 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.[32] Structure of the languageThe 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 tree of linked lists with the links proceeding from the latest (most recently) defined word to the oldest, until a sentinel value, usually a NULL pointer, is found. A context switch causes a list search to start at a different leaf. A linked list search continues as the branch merges into the main trunk leading eventually back to the sentinel, the root. There can be several dictionaries. In rare cases such as meta-compilation a dictionary might be isolated and stand-alone. The effect resembles that of nesting namespaces and can overload keywords depending on the context. 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 systems) 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.[33] The exact format of a dictionary entry is not prescribed, and implementations vary. Structure of the compilerThe compiler itself is not a monolithic program. It consists of Forth words visible to the system, and usable by a programmer. 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.[28] The classic examples of compile-time words are the control structures such as ... DUP 6 < IF DROP 5 ELSE 1 - THEN ...
would often be compiled to the following sequence inside a definition: ... DUP LIT 6 < ?BRANCH 5 DROP LIT 5 BRANCH 3 LIT 1 - ...
The numbers after Compilation state and interpretation stateThe word The word The interpreter state can be changed manually with the words In ANS Forth, the current state of the interpreter can be read from the flag Immediate wordsThe word Instead of reserving space for an Immediate flag in every definition, some implementations of Forth use an Immediates Dictionary which is checked first when in compile mode. Unnamed words and execution tokensIn ANS Forth, unnamed words can be defined with the word Execution tokens can be stored in variables. The word The word Parsing words and commentsThe words Structure of codeIn most Forth systems, the body of a code definition consists of either machine language, or some form of threaded code. The original Forth which follows the informal FIG standard (Forth Interest Group), is a TIL (Threaded Interpretive Language). This is also called indirect-threaded code, but direct-threaded and subroutine threaded Forths have also become popular in modern times. The fastest modern Forths, such as SwiftForth, VFX Forth, and iForth, compile Forth to native machine code. Data objectsWhen 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:
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).[38] 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. Examples“Hello, World!” : HELLO ( -- ) CR ." Hello, World!" ;
HELLO <cr> Hello, World! The 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!)
The word Mixing states of compiling and interpretingHere is the definition of a word : EMIT-Q 81 ( the ASCII value for the character 'Q' ) EMIT ;
This definition was written to use the ASCII value of the The following redefinition of : EMIT-Q [ CHAR Q ] LITERAL EMIT ;
The parsing word : EMIT-Q [CHAR] Q EMIT ; \ Emit the single character 'Q'
This definition used Both : [CHAR] CHAR POSTPONE LITERAL ; IMMEDIATE
RC4 cipher programIn 1987, Ron Rivest developed the RC4 cipher-system for RSA Data Security, Inc. Its description follows:
The following Standard Forth version uses Core and Core Extension words only. 0 value ii 0 value jj
0 value KeyAddr 0 value KeyLen
create SArray 256 allot \ state array of 256 bytes
: KeyArray KeyLen mod KeyAddr ;
: get_byte + c@ ;
: set_byte + c! ;
: as_byte 255 and ;
: reset_ij 0 TO ii 0 TO jj ;
: i_update 1 + as_byte TO ii ;
: j_update ii SArray get_byte + as_byte TO jj ;
: swap_s_ij
jj SArray get_byte
ii SArray get_byte jj SArray set_byte
ii SArray set_byte
;
: rc4_init ( KeyAddr KeyLen -- )
256 min TO KeyLen TO KeyAddr
256 0 DO i i SArray set_byte LOOP
reset_ij
BEGIN
ii KeyArray get_byte jj + j_update
swap_s_ij
ii 255 < WHILE
ii i_update
REPEAT
reset_ij
;
: rc4_byte
ii i_update jj j_update
swap_s_ij
ii SArray get_byte jj SArray get_byte + as_byte SArray get_byte xor
;
This is one way to test the code: hex
create AKey 61 c, 8A c, 63 c, D2 c, FB c,
: test cr 0 DO rc4_byte . LOOP cr ;
AKey 5 rc4_init
2C F9 4C EE DC 5 test \ output should be: F1 38 29 C9 DE
ImplementationsBecause Forth is simple to implement and has no standard reference implementation, there are numerous versions of the language. In addition to supporting the standard varieties of desktop computer systems (POSIX, Microsoft Windows, macOS), many of these Forth systems also target a variety of embedded systems. Listed here are some of the systems which conform to the 1994 ANS Forth standard.
See also
NotesReferences
External links
Wikimedia Commons has media related to Forth (programming language). Wikibooks has a book on the topic of: Forth |
Portal di Ensiklopedia Dunia