开发者

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.


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).


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜