Question

I am trying to understand how to apply Visitor pattern once I have an AST generated from ANTLR Grammar. Is it different approach than traversing a tree?

For example, assume I have the following AST (From this question):

enter image description here

If I want to appened FUNDEF ids to all its VARDECL ids, my approach is to do a tree traversal to find all VARDECL inside BLOCK and add a new child with (FUNDEF id + old_name) and remove the old one.

Is this the correct approach or would somehow visitor pattern work best? If visitor pattern, what would be the sample code in this specific case?

Thanks in advance!

Was it helpful?

Solution

I doubt the visitor pattern would help here. It is used when you have a data structure and take this to every node for changes. A typical case for this as described in "Head First Design Patterns" by Freeman & Freeman is ordering a Coffee. This is your object that visits each compositor for additional information (milk, sugar).

Your original idea of using a tree walk to modify the AST is probably the best option you have.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top