May the Forth be With You – Programs

In which I create a state machine and compile simple programs but I don’t implement branches

Provide builtin branch and branch? words.

Seems simple enough…

… oh wait, how can I branch somewhere if I don’t have the concept of a program, or a list of words at the least. I’ll create the words for now, but I won’t do any implementation.

Implement : and ; and compile-mode in your interpreter.

So this is still relatively simple. My Forth machine now has to have states ie. compiling and interpreting. So I introduced a state machine with three states.

	fileprivate enum State: StateType
		case interpreting
		case needWordName
		case compiling

		func canTransition(to: MyForth.State) -> TransitionShould<MyForth.State>
			switch (self, to)
			case (.interpreting, .needWordName),
				 (.needWordName, .compiling),
				 (.compiling, .interpreting):
				return .carryOn
				return .redirect(.interpreting)

You can go from interpreting to needWordName to compiling and then back to interpreting.

The State Machine

You can also go back from anywhere to interpreting but this is considered to be an error and, if such a route is followed, it is detected and an exception thrown.

The reason there is a state needsWordName is because we need to remember that the Forth machine is looking for a word name, if it reaches the end of the current word stream, we need to be aware that the first word in the next word stream is the name part of a definition.

I factored out the part of the interpreter loop that loops through a sequence of words so that I can call it with a sequence of words, not a sequence of Character. The old interpreter function now just creates an InputParser which is just a sequence of words and passes it to the new function. This means that, to execute a word in the dictionary that is not a primitive, we just pull up its associated list of words and recursively call the interpreter function. The Forth return stack is thus implicit in the Swift stack.

The code for this post is here:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.