max
max

Reputation: 41

Constructing an Interpreter in Smalltalk

I need to build an interpreter in smalltalk language. It will interpret a simple language with few fixed instruction set, there are only 2 data types in it and it evaluates the expression in a postfix fashion. The language itself is interpreted line by line and interpreter will throw an error on encountering wrong instruction set.

Please help, how to start with this interpreter. What kinda data structures should be used to pull data from the user input and evaluate it according to the instruction set of the language.

Thanks.

Upvotes: 2

Views: 684

Answers (3)

Géal
Géal

Reputation: 1482

Before interpreting the language itself, you should use a separate parser to ensure the expression is well formed. PetitParser may be useful for that.

Upvotes: 0

Alex Jasmin
Alex Jasmin

Reputation: 39516

That doesn't sound too hard to implement.

Postfix languages are easily implemented using a stack. In Smalltalk a stack can be an OrderedCollection on which you use the addLast: and removeLast methods.

If the language is interpreted line by line your interpreter main loop may look something like:

instructions := sourceCode subStrings: (Character cr asString).
instructions do: [:eachInstruction | ...]

One way to structure the code would be to create an Interpreter class which has a stack member variable and a method for each language instruction.

These instruction methods may look something like:

addInstruction
| op1 op2 |
op1  := stack removeLast.
op2  := stack removeLast.
stack addLast: (op1 + op2).

Upvotes: 2

Preet Sangha
Preet Sangha

Reputation: 65555

If you are building a postfix notation interpreter you're sort of building a forth interpreter. There are loads of links to forth resources here.

Upvotes: 1

Related Questions