Different Architecure for VMTranslator

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Different Architecure for VMTranslator

Marco Bellocchi
Hi all,

While I like the implementation that is suggested in the book and in the lectures, you might want to consider also a different one if you are using an OO programming like java or C# and you are familiar with the Visitor design pattern. This is by no mean necessary here but you might be interested in playing with the Visitor pattern and see a case in which it is actually used.

What you could have is a Parser class which has the responsibility to parse the vm file content and it creates a list (a vector) of IVMCommands. IVMCommand is just an interface with a single method which accept an IVisitor: void Accept(IVisitor visitor) (your list of commands is basically your "abstract syntax tree"). I will explain IVisitor interface later.

You will have concrete implementations of IVMCommand, for example VMAddCommand, VMSubCommand, VMOrCommand, VMStaticCommand and so on (non necessarily one class per operation, you can find a simpliified hierarchy), and each class just implements the Accept method (it simply does visitor.Visit(this))

Now IVisitor is an interface containing methods, one per concrete implementation of IVMCommand, so:

void Visit(VMAddCommand);
void Visit(VMSubCommand);
...

Now you can have an implementation of this interface, like VmTranslatorVisitor, in which in each Visit method you just build the assembly snippet code that corresponds to the command that has been visited.

You will need then a "controller" class that has the responsibility to instantiate Parser and a concrete implementation of IVisitor (like VmTranslatorVisitor) in such a way that you will get out your final assembly code...

Now the beauty of this is that if at some point if you want to create a VMTranslator for x86 platform, what you really need to do is just implement IVisitor class and that's it, so you could easily target any other platform, without touching you command hierarchy or any part of the other code, fulfilling the open\closed principle ;)

In this case the usage of the Visitor pattern it is a bit forced in the sense that you really don't have a real abstract syntax tree to visit (it is a list not really a tree) and the suggested implementation is definitely simpler, however I think it is still a good example to get your hands dirty with this nice pattern.

Loading...