Forth (programming language)

From Wikipedia for FEVERv2
Jump to navigation Jump to search

"FORTH" redirects here. Forth (programming language)_sentence_0

For other uses, see Forth (disambiguation). Forth (programming language)_sentence_1

Forth (programming language)_table_infobox_0

ForthForth (programming language)_table_caption_0
ParadigmForth (programming language)_header_cell_0_0_0 Procedural, stack-oriented, reflective, concatenativeForth (programming language)_cell_0_0_1
Designed byForth (programming language)_header_cell_0_1_0 Charles H. MooreForth (programming language)_cell_0_1_1
First appearedForth (programming language)_header_cell_0_2_0 1970; 50 years ago (1970)Forth (programming language)_cell_0_2_1
Typing disciplineForth (programming language)_header_cell_0_3_0 typelessForth (programming language)_cell_0_3_1
Major implementationsForth (programming language)_header_cell_0_4_0
Influenced byForth (programming language)_header_cell_0_5_0
InfluencedForth (programming language)_header_cell_0_6_0

Forth is an imperative stack-based computer programming language and environment originally designed by Chuck Moore. Forth (programming language)_sentence_2

Language features include structured programming, reflection (the ability to examine and modify program structure during execution), concatenative programming (functions are composed with juxtaposition) and extensibility (the programmer can create new commands). Forth (programming language)_sentence_3

Although not an acronym, the language's name is sometimes spelled with all capital letters as FORTH, following the customary usage during its earlier years. Forth (programming language)_sentence_4

A procedural programming language without type checking, Forth features both interactive execution of commands (making it suitable as a shell for systems that lack a more formal operating system) and the ability to compile sequences of commands for later execution. Forth (programming language)_sentence_5

For much of Forth's existence, the standard technique was to compile to threaded code, but there are modern implementations that generate optimized machine code like other language compilers. Forth (programming language)_sentence_6

Forth is used in the Open Firmware boot loader, in space applications such as the Philae spacecraft, and in other embedded systems which involve interaction with hardware. Forth (programming language)_sentence_7

The bestselling 1986 computer game Starflight, from Electronic Arts, was written with a custom Forth. Forth (programming language)_sentence_8

The free software Gforth implementation is actively maintained, as are several commercially supported systems. Forth (programming language)_sentence_9

Overview Forth (programming language)_section_0

Forth is a simple, yet extensible language; its modularity and extensibility permit writing significant programs. Forth (programming language)_sentence_10

A Forth environment combines the compiler with an interactive shell, where the user defines and runs subroutines called words. Forth (programming language)_sentence_11

Words can be tested, redefined, and debugged as the source is entered without recompiling or restarting the whole program. Forth (programming language)_sentence_12

Thus Forth programmers enjoy the immediacy of an interpreter while at the same time the performance and efficiency of a compiler. Forth (programming language)_sentence_13

All syntactic elements, including variables and basic operators, are defined as words. Forth (programming language)_sentence_14

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. Forth (programming language)_sentence_15

The Forth philosophy emphasizes the use of small, simple words (subroutines) that perform the fewest functions possible. Forth (programming language)_sentence_16

Words for bigger tasks would call upon many smaller words that each accomplish a distinct sub-task. Forth (programming language)_sentence_17

These in turn invoke ever-smaller words to contribute to the goals and intermediate goals of the words at higher levels. Forth (programming language)_sentence_18

Thus a large Forth program will consist of a hierarchy of words, each being the smallest and simplest possible for its level. Forth (programming language)_sentence_19

These words, being distinct modules that communicate (pass data) implicitly via a stack mechanism, can be prototyped, built and tested independently. Forth (programming language)_sentence_20

This program structure facilitates fast and easy development, both top-down and bottom-up. Forth (programming language)_sentence_21

It also makes for versatile program modification to meet ever-changing requirements. Forth (programming language)_sentence_22

The ability to create new words and add them to the environment vocabulary (Forth's extensibility) permit the programmer to craft solution-oriented code tailored to the specific programming problem at hand. Forth (programming language)_sentence_23

The highest level of Forth code will resemble an English-language description of the application. Forth (programming language)_sentence_24

Forth has been called a “meta-application language” — a language that can be used to create problem-oriented languages. Forth (programming language)_sentence_25

Stacks Forth (programming language)_section_1

Most programming environments with recursive subroutines use a stack for control flow. Forth (programming language)_sentence_26

This structure typically also stores local variables, including subroutine parameters (in call by value system such as C). Forth (programming language)_sentence_27

Forth often does not have local variables, however, nor is it call-by-value. Forth (programming language)_sentence_28

Instead, intermediate values are kept in another stack, different from the one it uses for return addresses, loop counters, etc. Forth (programming language)_sentence_29

Words operate directly on the topmost values in the first of these two stacks. Forth (programming language)_sentence_30

It may, therefore, be called the "parameter" or "data" stack, but most often simply "the" stack. Forth (programming language)_sentence_31

The second, function-call stack is then called the "linkage" or "return" stack, abbreviated rstack. Forth (programming language)_sentence_32

Special rstack manipulation functions provided by the kernel allow it to be used for temporary storage within a word, and it is often used by counted loops, but otherwise it cannot be used to pass parameters or manipulate data. Forth (programming language)_sentence_33

Most words are specified in terms of their effect on the stack. Forth (programming language)_sentence_34

Typically, parameters are placed on the top of the stack before the word executes. Forth (programming language)_sentence_35

After execution, the parameters have been erased and replaced with any return values. Forth (programming language)_sentence_36

For arithmetic operators, this follows the rule of reverse Polish notation. Forth (programming language)_sentence_37

See below for examples illustrating stack usage. Forth (programming language)_sentence_38

Uses Forth (programming language)_section_2

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. Forth (programming language)_sentence_39

Forth has a niche both in astronomical and space applications. Forth (programming language)_sentence_40

Forth is still used today in many embedded systems (small computerized devices) because of its portability, efficient memory use, short development times, and high execution speed. Forth (programming language)_sentence_41

It has been implemented efficiently on modern reduced instruction set computers, and processors that use Forth as machine language have been produced. Forth (programming language)_sentence_42

Other uses of Forth include the Open Firmware boot ROMs used by Apple, IBM, Sun, and OLPC XO-1. Forth (programming language)_sentence_43

History Forth (programming language)_section_3

Forth evolved from Charles H. Moore's personal programming system, which had been in continuous development since 1968. Forth (programming language)_sentence_44

Forth was first exposed to other programmers in the early 1970s, starting with Elizabeth Rather at the United States National Radio Astronomy Observatory (NRAO). Forth (programming language)_sentence_45

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. Forth (programming language)_sentence_46

Forth is so-named, because in 1968 "the file holding the interpreter was labeled FOURTH, for 4th (next) generation software, but the IBM 1130 operating system restricted file names to five characters." Forth (programming language)_sentence_47

Moore saw Forth as a successor to compile-link-go third-generation programming languages, or software for "fourth generation" hardware, not a fourth-generation programming language as the term has come to be used. Forth (programming language)_sentence_48

As Charles Moore frequently moved from job to job over his career, an early pressure on the developing language was ease of porting to different computer architectures. Forth (programming language)_sentence_49

A Forth system has often been used to bring up new hardware. Forth (programming language)_sentence_50

For example, Forth was the first resident software on the new Intel 8086 chip in 1978 and MacFORTH was the first resident development system for the 128K Macintosh in 1984. Forth (programming language)_sentence_51

FORTH, Inc.'s microFORTH was developed for the Intel 8080, Motorola 6800, Zilog Z80, and RCA 1802 () microprocessors, starting in 1976. Forth (programming language)_sentence_52

MicroFORTH was later used by hobbyists to generate Forth systems for other architectures, such as the 6502 in 1978. Forth (programming language)_sentence_53

Wide dissemination finally led to standardization of the language. Forth (programming language)_sentence_54

Common practice was codified in the de facto standards FORTH-79 and FORTH-83 in the years 1979 and 1983, respectively. Forth (programming language)_sentence_55

These standards were unified by ANSI in 1994, commonly referred to as ANS Forth. Forth (programming language)_sentence_56

Forth became popular in the 1980s because it was well suited to the small microcomputers of that time, being compact and portable. Forth (programming language)_sentence_57

Forth is also easy to implement, leading to a large number of implementations. Forth (programming language)_sentence_58

At least one home computer, the British Jupiter ACE, had Forth in its ROM-resident operating system. Forth (programming language)_sentence_59

The Canon Cat also used Forth for its system programming, and Rockwell produced single-chip microcomputers with resident Forth kernels, the R65F11 and R65F12. Forth (programming language)_sentence_60

Insoft is a version of Forth with graphics extensions for the Apple II. Forth (programming language)_sentence_61

ASYST was a Forth expansion for measuring and controlling on PCs. Forth (programming language)_sentence_62

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. Forth (programming language)_sentence_63

Programmer's perspective Forth (programming language)_section_4

Further information: Reverse Polish notation Forth (programming language)_sentence_64

Forth relies heavily on explicit use of a data stack and reverse Polish notation (RPN or postfix notation), commonly used in calculators from Hewlett-Packard. Forth (programming language)_sentence_65

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. Forth (programming language)_sentence_66

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. Forth (programming language)_sentence_67

Extending the compiler only requires writing a new word, instead of modifying a grammar and changing the underlying implementation. Forth (programming language)_sentence_68

Using RPN, one could get the result of the mathematical expression (25 * 10 + 50) this way: Forth (programming language)_sentence_69

This command line first puts the numbers 25 and 10 on the implied stack. Forth (programming language)_sentence_70

The word * multiplies the two numbers on the top of the stack and replaces them with their product. Forth (programming language)_sentence_71

Then the number 50 is placed on the stack. Forth (programming language)_sentence_72

The word + adds it to the previous product. Forth (programming language)_sentence_73

The CR moves the output to a new line (it is only for formatting purposes and could be omitted but—in most implementations—without it the output would occur on the same line as the input and would be less readable in the example). Forth (programming language)_sentence_74

Finally, the . Forth (programming language)_sentence_75

command prints the result to the user's terminal. Forth (programming language)_sentence_76

As everything has completed successfully at that point, the text interpreter then outputs the prompt OK and moves to a new line to get more input without needing anything explicit to do that. Forth (programming language)_sentence_77

Even Forth's structural features are stack-based. Forth (programming language)_sentence_78

For example: Forth (programming language)_sentence_79

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 FLOOR5. Forth (programming language)_sentence_80

The text in parentheses is a comment, advising that this word expects a number on the stack and will return a possibly changed number (on the stack). Forth (programming language)_sentence_81

The subroutine uses the following commands: DUP duplicates the number on the stack; 6 pushes a 6 on top of the stack; < compares the top two numbers on the stack (6 and the DUPed input), and replaces them with a true-or-false value; IF takes a true-or-false value and chooses to execute commands immediately after it or to skip to the ELSE; DROP discards the value on the stack; 5 pushes a 5 on top of the stack; and THEN ends the conditional. Forth (programming language)_sentence_82

The FLOOR5 word is equivalent to this function written in the C programming language using the ternary operator '? Forth (programming language)_sentence_83

' Forth (programming language)_sentence_84

This function is written more succinctly as: Forth (programming language)_sentence_85

You could run this word as follows: Forth (programming language)_sentence_86

First the interpreter pushes a number (1 or 8) onto the stack, then it calls FLOOR5 , which pops off this number again and pushes the result. Forth (programming language)_sentence_87

The CR moves the output to a new line (again, this is only here for readability). Forth (programming language)_sentence_88

Finally, a call to . Forth (programming language)_sentence_89

pops the result and prints it to the user's terminal. Forth (programming language)_sentence_90

Facilities Forth (programming language)_section_5

Forth's grammar has no official specification. Forth (programming language)_sentence_91

Instead, it is defined by simple algorithm. Forth (programming language)_sentence_92

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. Forth (programming language)_sentence_93

When the interpreter finds a word, it looks the word up in the dictionary. Forth (programming language)_sentence_94

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. Forth (programming language)_sentence_95

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. Forth (programming language)_sentence_96

Otherwise, if both the lookup and the number conversion fail, 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. Forth (programming language)_sentence_97

The definition of a new word is started with the word : (colon) and ends with the word ; (semi-colon). Forth (programming language)_sentence_98

For example, Forth (programming language)_sentence_99

will compile the word X, and makes the name findable in the dictionary. Forth (programming language)_sentence_100

When executed by typing 10 X at the console this will print 11 10. Forth (programming language)_sentence_101

Most Forth systems include an assembler that allows one to specify words using the processor's facilities at its lowest level. Forth (programming language)_sentence_102

Mostly the assembler is tucked away in a separate namespace (wordlist) as relatively few users want to use it. Forth (programming language)_sentence_103

Forth assemblers may use a reverse-polish syntax in which the parameters of an instruction precede the instruction, but designs vary widely and are specific to the Forth implementation. Forth (programming language)_sentence_104

A typical reverse-polish assembler prepares the operands on the stack and have the mnemonic copy the whole instruction into memory as the last step. Forth (programming language)_sentence_105

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. "datastackpointer" for the register used as a stack pointer. Forth (programming language)_sentence_106

Operating system, files, and multitasking Forth (programming language)_section_6

Most 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. Forth (programming language)_sentence_107

All modern Forth systems use normal text files for source, even if they are embedded. Forth (programming language)_sentence_108

An embedded system with a resident compiler gets its source via a serial line. Forth (programming language)_sentence_109

Classic Forth systems traditionally use neither operating system nor . Forth (programming language)_sentence_110

Instead of storing code in files, source code is stored in disk blocks written to physical disk addresses. Forth (programming language)_sentence_111

The word BLOCK 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. Forth (programming language)_sentence_112

Block use has become rare since the mid-1990s. Forth (programming language)_sentence_113

In a hosted system those blocks too are allocated in a normal file in any case. Forth (programming language)_sentence_114

Multitasking, most commonly cooperative round-robin scheduling, is normally available (although multitasking words and support are not covered by the ANSI Forth Standard). Forth (programming language)_sentence_115

The word PAUSE is used to save the current task's execution context, to locate the next task, and restore its execution context. Forth (programming language)_sentence_116

Each task has its own stacks, private copies of some control variables and a scratch area. Forth (programming language)_sentence_117

Swapping tasks is simple and efficient; as a result, Forth multitaskers are available even on very simple microcontrollers, such as the Intel 8051, Atmel AVR, and TI MSP430. Forth (programming language)_sentence_118

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. Forth (programming language)_sentence_119

Typically they have a larger and different set of words from the stand-alone Forth's PAUSE word for task creation, suspension, destruction and modification of priority. Forth (programming language)_sentence_120

Self-compilation and cross compilation Forth (programming language)_section_7

A 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). Forth (programming language)_sentence_121

The usual method is to redefine the handful of words that place compiled bits into memory. Forth (programming language)_sentence_122

The compiler's words use specially named versions of fetch and store that can be redirected to a buffer area in memory. Forth (programming language)_sentence_123

The buffer area simulates or accesses a memory area beginning at a different address than the code buffer. Forth (programming language)_sentence_124

Such compilers define words to access both the target computer's memory, and the host (compiling) computer's memory. Forth (programming language)_sentence_125

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. Forth (programming language)_sentence_126

This effectively reuses all the code of the compiler and interpreter. Forth (programming language)_sentence_127

Then, the Forth system's code is compiled, but this version is stored in the buffer. Forth (programming language)_sentence_128

The buffer in memory is written to disk, and ways are provided to load it temporarily into memory for testing. Forth (programming language)_sentence_129

When the new version appears to work, it is written over the previous version. Forth (programming language)_sentence_130

Numerous variations of such compilers exist for different environments. Forth (programming language)_sentence_131

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. Forth (programming language)_sentence_132

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. Forth (programming language)_sentence_133

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. Forth (programming language)_sentence_134

Structure of the language Forth (programming language)_section_8

The basic data structure of Forth is the "dictionary" which maps "words" to executable code or named data structures. Forth (programming language)_sentence_135

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. Forth (programming language)_sentence_136

A context switch causes a list search to start at a different leaf. Forth (programming language)_sentence_137

A linked list search continues as the branch merges into the main trunk leading eventually back to the sentinel, the root. Forth (programming language)_sentence_138

There can be several dictionaries. Forth (programming language)_sentence_139

In rare cases such as meta-compilation a dictionary might be isolated and stand-alone. Forth (programming language)_sentence_140

The effect resembles that of nesting namespaces and can overload keywords depending on the context. Forth (programming language)_sentence_141

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). Forth (programming language)_sentence_142

Head and body of a dictionary entry are treated separately because they may not be contiguous. Forth (programming language)_sentence_143

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. Forth (programming language)_sentence_144

In some environments (such as embedded systems) the heads occupy memory unnecessarily. Forth (programming language)_sentence_145

However, some cross-compilers may put heads in the target if the target itself is expected to support an interactive Forth. Forth (programming language)_sentence_146

Dictionary entry Forth (programming language)_section_9

The exact format of a dictionary entry is not prescribed, and implementations vary. Forth (programming language)_sentence_147

However, certain components are almost always present, though the exact size and order may vary. Forth (programming language)_sentence_148

Described as a structure, a dictionary entry might look this way: Forth (programming language)_sentence_149

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. Forth (programming language)_sentence_150

The character representation of the word's name then follows the prefix. Forth (programming language)_sentence_151

Depending on the particular implementation of Forth, there may be one or more NUL ('\0') bytes for alignment. Forth (programming language)_sentence_152

The link field contains a pointer to the previously defined word. Forth (programming language)_sentence_153

The pointer may be a relative displacement or an absolute address that points to the next oldest sibling. Forth (programming language)_sentence_154

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. Forth (programming language)_sentence_155

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. Forth (programming language)_sentence_156

This is the same as what a processor's call/return instructions do. Forth (programming language)_sentence_157

Structure of the compiler Forth (programming language)_section_10

The compiler itself is not a monolithic program. Forth (programming language)_sentence_158

It consists of Forth words visible to the system, and usable by a programmer. Forth (programming language)_sentence_159

This allows a programmer to change the compiler's words for special purposes. Forth (programming language)_sentence_160

The "compile time" flag in the name field is set for words with "compile time" behavior. Forth (programming language)_sentence_161

Most simple words execute the same code whether they are typed on a command line, or embedded in code. Forth (programming language)_sentence_162

When compiling these, the compiler simply places code or a threaded pointer to the word. Forth (programming language)_sentence_163

The classic examples of compile-time words are the control structures such as IF and WHILE. Forth (programming language)_sentence_164

Almost all of Forth's control structures and almost all of its compiler are implemented as compile-time words. Forth (programming language)_sentence_165

Apart from some rarely used control flow words only found in a few implementations, such as a conditional return, all of Forth's control flow words are executed during compilation to compile various combinations of primitive words along with their branch addresses. Forth (programming language)_sentence_166

For instance, IF and WHILE, and the words that match with those, set up BRANCH (unconditional branch) and ?BRANCH (pop a value off the stack, and branch if it is false). Forth (programming language)_sentence_167

Counted loop control flow words work similarly but set up combinations of primitive words that work with a counter, and so on. Forth (programming language)_sentence_168

During compilation, the data stack is used to support control structure balancing, nesting, and back-patching of branch addresses. Forth (programming language)_sentence_169

The snippet: Forth (programming language)_sentence_170

would be compiled to the following sequence inside a definition: Forth (programming language)_sentence_171

The numbers after BRANCH represent relative jump addresses. Forth (programming language)_sentence_172

LIT is the primitive word for pushing a "literal" number onto the data stack. Forth (programming language)_sentence_173

Compilation state and interpretation state Forth (programming language)_section_11

The word : (colon) parses a name as a parameter, creates a dictionary entry (a colon definition) and enters compilation state. Forth (programming language)_sentence_174

The interpreter continues to read space-delimited words from the user input device. Forth (programming language)_sentence_175

If a word is found, the interpreter executes the compilation semantics associated with the word, instead of the interpretation semantics. Forth (programming language)_sentence_176

The default compilation semantics of a word are to append its interpretation semantics to the current definition. Forth (programming language)_sentence_177

The word ; (semi-colon) finishes the current definition and returns to interpretation state. Forth (programming language)_sentence_178

It is an example of a word whose compilation semantics differ from the default. Forth (programming language)_sentence_179

The interpretation semantics of ; (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. Forth (programming language)_sentence_180

The interpreter state can be changed manually with the words [ (left-bracket) and ] (right-bracket) which enter interpretation state or compilation state, respectively. Forth (programming language)_sentence_181

These words can be used with the word LITERAL to calculate a value during a compilation and to insert the calculated value into the current colon definition. Forth (programming language)_sentence_182

LITERAL 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. Forth (programming language)_sentence_183

In ANS Forth, the current state of the interpreter can be read from the flag STATE which contains the value true when in compilation state and false otherwise. Forth (programming language)_sentence_184

This allows the implementation of so-called state-smart words with behavior that changes according to the current state of the interpreter. Forth (programming language)_sentence_185

Immediate words Forth (programming language)_section_12

The word IMMEDIATE marks the most recent colon definition as an immediate word, effectively replacing its compilation semantics with its interpretation semantics. Forth (programming language)_sentence_186

Immediate words are normally executed during compilation, not compiled, but this can be overridden by the programmer in either state. Forth (programming language)_sentence_187

is an example of an immediate word. Forth (programming language)_sentence_188

In ANS Forth, the word POSTPONE 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 (programming language)_sentence_189

Forth-83 defined separate words COMPILE and [COMPILE] to force the compilation of non-immediate and immediate words, respectively. Forth (programming language)_sentence_190

Unnamed words and execution tokens Forth (programming language)_section_13

In ANS Forth, unnamed words can be defined with the word :NONAME which compiles the following words up to the next ; (semi-colon) and leaves an execution token on the data stack. Forth (programming language)_sentence_191

The execution token provides an opaque handle for the compiled semantics, similar to the function pointers of the C programming language. Forth (programming language)_sentence_192

Execution tokens can be stored in variables. Forth (programming language)_sentence_193

The word EXECUTE takes an execution token from the data stack and performs the associated semantics. Forth (programming language)_sentence_194

The word COMPILE, (compile-comma) takes an execution token from the data stack and appends the associated semantics to the current definition. Forth (programming language)_sentence_195

The word ' (tick) takes the name of a word as a parameter and returns the execution token associated with that word on the data stack. Forth (programming language)_sentence_196

In interpretation state, ' RANDOM-WORD EXECUTE is equivalent to RANDOM-WORD. Forth (programming language)_sentence_197

Parsing words and comments Forth (programming language)_section_14

The words : (colon), POSTPONE, ' (tick) are examples of parsing words that take their arguments from the user input device instead of the data stack. Forth (programming language)_sentence_198

Another example is the word ( (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. Forth (programming language)_sentence_199

Similarly, the word \ (backslash) is used for comments that continue to the end of the current line. Forth (programming language)_sentence_200

To be parsed correctly, ( (paren) and \ (backslash) must be separated by whitespace from the following comment text. Forth (programming language)_sentence_201

Structure of code Forth (programming language)_section_15

In most Forth systems, the body of a code definition consists of either machine language, or some form of threaded code. Forth (programming language)_sentence_202

The original Forth which follows the informal FIG standard (Forth Interest Group), is a TIL (Threaded Interpretive Language). Forth (programming language)_sentence_203

This is also called indirect-threaded code, but direct-threaded and subroutine threaded Forths have also become popular in modern times. Forth (programming language)_sentence_204

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. Forth (programming language)_sentence_205

Data objects Forth (programming language)_section_16

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. Forth (programming language)_sentence_206

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. Forth (programming language)_sentence_207

Examples include: Forth (programming language)_sentence_208

Forth (programming language)_description_list_0

  • VARIABLE: Names an uninitialized, one-cell memory location. Instance behavior of a VARIABLE returns its address on the stack.Forth (programming language)_item_0_0
  • CONSTANT: Names a value (specified as an argument to CONSTANT). Instance behavior returns the value.Forth (programming language)_item_0_1
  • CREATE: 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 (programming language)_item_0_2

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. Forth (programming language)_sentence_209

Some examples include circular buffers, named bits on an I/O port, and automatically indexed arrays. Forth (programming language)_sentence_210

Data objects defined by these and similar words are global in scope. Forth (programming language)_sentence_211

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 language)_sentence_212

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). Forth (programming language)_sentence_213

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. Forth (programming language)_sentence_214

Programming Forth (programming language)_section_17

Words written in Forth are compiled into an executable form. Forth (programming language)_sentence_215

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). Forth (programming language)_sentence_216

Some systems have optimizing compilers. Forth (programming language)_sentence_217

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. Forth (programming language)_sentence_218

During development, the programmer uses the interpreter in REPL mode to execute and test each little piece as it is developed. Forth (programming language)_sentence_219

Most Forth programmers therefore advocate a loose top-down design, and bottom-up development with continuous testing and integration. Forth (programming language)_sentence_220

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. Forth (programming language)_sentence_221

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. Forth (programming language)_sentence_222

Code examples Forth (programming language)_section_18

“Hello, World!” Forth (programming language)_section_19

For an explanation of the tradition of programming "Hello, World! Forth (programming language)_sentence_223

", see "Hello, World!" Forth (programming language)_sentence_224 program. Forth (programming language)_sentence_225

One possible implementation: Forth (programming language)_sentence_226

The word CR (Carriage Return) causes the following output to be displayed on a new line. Forth (programming language)_sentence_227

The parsing word ." Forth (programming language)_sentence_228

(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. Forth (programming language)_sentence_229

The space character separating the word ." Forth (programming language)_sentence_230

from the string Hello, World! Forth (programming language)_sentence_231

is not included as part of the string. Forth (programming language)_sentence_232

It is needed so that the parser recognizes ." Forth (programming language)_sentence_233

as a Forth word. Forth (programming language)_sentence_234

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: Forth (programming language)_sentence_235

. Forth (programming language)_sentence_236

( (dot-paren) is an immediate word that parses a parenthesis-delimited string and displays it. Forth (programming language)_sentence_237

As with the word ." Forth (programming language)_sentence_238

the space character separating . Forth (programming language)_sentence_239

( from Hello, World! Forth (programming language)_sentence_240

is not part of the string. Forth (programming language)_sentence_241

The word CR comes before the text to print. Forth (programming language)_sentence_242

By convention, the Forth interpreter does not start output on a new line. Forth (programming language)_sentence_243

Also by convention, the interpreter waits for input at the end of the previous line, after an ok prompt. Forth (programming language)_sentence_244

There is no implied "flush-buffer" action in Forth's CR, as sometimes is in other programming languages. Forth (programming language)_sentence_245

Mixing states of compiling and interpreting Forth (programming language)_section_20

Here is the definition of a word EMIT-Q which when executed emits the single character Q: Forth (programming language)_sentence_246

This definition was written to use the ASCII value of the Q character (81) directly. Forth (programming language)_sentence_247

The text between the parentheses is a comment and is ignored by the compiler. Forth (programming language)_sentence_248

The word EMIT takes a value from the data stack and displays the corresponding character. Forth (programming language)_sentence_249

The following redefinition of EMIT-Q uses the words [ (left-bracket), ] (right-bracket), CHAR and LITERAL to temporarily switch to interpreter state, calculate the ASCII value of the Q character, return to compilation state and append the calculated value to the current colon definition: Forth (programming language)_sentence_250

The parsing word CHAR takes a space-delimited word as parameter and places the value of its first character on the data stack. Forth (programming language)_sentence_251

The word [CHAR] is an immediate version of CHAR. Forth (programming language)_sentence_252

Using [CHAR], the example definition for EMIT-Q could be rewritten like this: Forth (programming language)_sentence_253

This definition used \ (backslash) for the describing comment. Forth (programming language)_sentence_254

Both CHAR and [CHAR] are predefined in ANS Forth. Forth (programming language)_sentence_255

Using IMMEDIATE and POSTPONE, [CHAR] could have been defined like this: Forth (programming language)_sentence_256

A complete RC4 cipher program Forth (programming language)_section_21

In 1987, Ron Rivest developed the RC4 cipher-system for RSA Data Security, Inc. Forth (programming language)_sentence_257

The code is extremely simple and can be written by most programmers from the description: Forth (programming language)_sentence_258

The following Standard Forth version uses Core and Core Extension words only. Forth (programming language)_sentence_259

This is one of many ways to test the code: Forth (programming language)_sentence_260

Implementations Forth (programming language)_section_22

Because the Forth virtual machine is simple to implement and has no standard reference implementation, there are numerous implementations of the language. Forth (programming language)_sentence_261

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. Forth (programming language)_sentence_262

Listed here are some of the more prominent systems which conform to the 1994 ANS Forth standard. Forth (programming language)_sentence_263

Forth (programming language)_unordered_list_1

  • Gforth, a portable ANS Forth implementation from the GNU ProjectForth (programming language)_item_1_3
  • , native code desktop and embedded Forths by Forth, Inc.Forth (programming language)_item_1_4
  • VFX Forth, highly-optimizing native code ForthForth (programming language)_item_1_5
  • Open Firmware, a bootloader and Firmware standard based on ANS ForthForth (programming language)_item_1_6
  • pForth, portable Forth written in CForth (programming language)_item_1_7
  • SP-Forth, ANS Forth implementation from the Russian Forth Interest Group (RuFIG)Forth (programming language)_item_1_8
  • , a very popular embedded forth with introduction here with an easy demo on desktop here using dockerForth (programming language)_item_1_9

See also Forth (programming language)_section_23

Forth (programming language)_unordered_list_2

  • colorForth, a later Forth-variant from Chuck MooreForth (programming language)_item_2_10
  • RTX2010, a CPU that runs Forth nativelyForth (programming language)_item_2_11
  • Joy, a functional language with similarities to ForthForth (programming language)_item_2_12
  • Factor, a language influenced by ForthForth (programming language)_item_2_13


Credits to the contents of this page go to the authors of the corresponding Wikipedia page: en.wikipedia.org/wiki/Forth (programming language).