If I want to create a model from the structure it turns out to be more difficult than I thought it would be. I'm using a visitor for this. In a typical visitor every element is treated in isolation. I can treat subelement B in the visitor but I cannot assign it to its parent A because there is no link. Â And I'm not really convinced that introducing return values in the visitor is the right way to go.
The refactoring engine essentially does that. The visitor is a big #collect: over the AST and each visit-method returns a new/modified element. I think this is the most natural thing to do in most cases.
What I need to do is a visitor that transforms one thing into another thing with having the need that existing parent-child relationships need to be preserved through the transformation.
Another approach would be to keep a stack of the elements visited. Like this you can always access the parents of the currently constructed elements. If I remember correctly, Pier has a few of those visitors. If you just need the direct parent, you can only remember the last parent in an instance variable, this is for example what OmniBrowser does when building UIs in OBBuilder. Alternatively you can also choose a different traversal strategy other than the canonical one from the root to the leaves. PetitParser has a couple of these visitors that traverse the graphs in "random" order keeping collections of processed and unprocessed items. There are many different ways of how you can visit your nodes. Each approach has its advantages and disadvantages in a particular use-case. So I guess you need to figure out yourself what works best for you. Lukas -- Lukas Renggli www.lukas-renggli.ch