Channels ▼
RSS

Parallel

JForth: Implementing Forth in Java


Java Implementation

You might first ask why I was motivated to implement Forth in Java and the answer would be to see how it might be done. Before being flamed, I should state the implementation I provide should really be called "Forth-like" as it stems from my recollection of how Forth works rather than a strict adherence to Forth standards. Also it was not done with any practical purpose in mind other than as a feasibility demonstration for fun. Finally, the Java implementation which I call "JForth," is not particularly efficient in terms of speed, memory usage, or anything else, but it served its purpose. The complete source code for JForth (packaged in a jar file which contains all of the javadocs, compiled classes, and source files) is available online.


Running JForth

Running JForth requires a Java 1.5 or newer JRE being available on your target machine. The jar file, Jforth.jar, available from DDJ, contains all of the javadocs, source code, test code and executable code required to run JForth. The code can either be run in a command shell directly out of the jar file using the command:

java -jar com.craigl.jforth.JForth

or the code can be extracted from the jar file and compiled in your preferred programming environment. Either way, once the main JForth class is executed you will be given the prompt > and the program will wait for you to enter Forth expressions. Type the Forth word "bye" to end your Forth session.

The file of test code, "testcode" must be extracted from the jar file to be executed. To compile and run this test code at the JForth prompt type:

>  "path_to_testcode_file/testcode" load <Enter>

In JForth, all words are derived from the abstract class BaseWord which implements the ExecuteIF interface. The BaseWord class maintains the name of the Forth word, a flag indicating whether the word is immediate or not and another flag indicating whether this word is a primitive.

The ExecuteIF interface consists of a single method that all words must implement:

public int execute(OStack dataStack, OStack variableStack);

This method takes references to the data and the variable stacks and returns a non-zero int value on success.

Derived from BaseWord are the PrimitiveWord and NonPrimitiveWord classes. Primitive words are defined in Java code; non-primitive words contain a list of BaseWords (both primitive and non-primitive) that make up the definition. A primitive word is executed by calling its execute method to run the Java code which makes up its definition. The execute method in a non-primitive word traverses its list of BaseWords calling the execute method of each sequentially. Listing Two shows the definition of the Forth multiplication operator as an example of how primitive words are implemented.

...
new PrimitiveWord("*", false, new ExecuteIF() {
	public int execute(OStack dStack, OStack vStack) {
	
	if (dStack.size() < 2)
		return 0;
	
	Object o1 = dStack.pop();
	Object o2 = dStack.pop();

	// Determine if both are of the same type
	if ((o1 instanceof Integer) && (o2 instanceof Integer)) {
		int i1 = ((Integer) o1).intValue();
		int i2 = ((Integer) o2).intValue();
		i2 *= i1;
		dStack.push(new Integer(i2));
		return 1;
	}	else	{
		System.out.println("* - cannot multiply strings");
		return 0;
		}
	}
  ...
Listing Two: Forth Multiply

The Forth dictionary is provided by the WordsList class which encapsulates a typed LinkedList. Helper methods in the class provide required functionality. Both the inner and the outer interpreters are methods in the JForth main class.

Two stacks are used in this implementation -- the data stack and the variable stack. Both use the stock Java Stack class. These stacks only contain objects. Currently the allowed objects on the stack are: Integers, Strings, BaseWords, and various types of control words used for conditional expressions and loop constructs. (Note: Since generics are used in this JForth implementation, Java 1.5 or newer must be used to compile and run the provided code.)

See the sidebar Running JForth to see how to run this code.

Typing "words" at the command line prompt will show you all available JForth words as shown below:

bye key random load array @ +! ! r@ r> >r variable constant forget wordsd words ; : hex decimal binary spaces cr . xor or and abs min max mod / * 2- 2+ 1- 1+ - + false true not 0> 0= 0< > = < depth rot over swap drop dup end begin +loop loop leave j i do else then if execute ' ( 

To see details about the defined words type "wordsd" at the command prompt.

Words:
Name: "bye", Primitive: true, Immediate: false
Name: "key", Primitive: true, Immediate: false
Name: "random", Primitive: true, Immediate: false
Name: "load", Primitive: true, Immediate: false
Name: "array", Primitive: true, Immediate: false

Most of the words implemented in JForth work as they do in Forth. To understand behavior in detail, consult the file JForth.java (available in JForth.jar) where all of the primitive words are defined.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video