Relative Content

Tag Archive for visitor-pattern

Implementing the Visitor Pattern for an Abstract Syntax Tree

I’m in the process of creating my own programming language, which I do for learning purposes. I already wrote the lexer and a recursive descent parser for a subset of my language (I currently support mathematical expressions, such as + - * / and parenthesis). The parser hands me back an Abstract Syntax Tree, on which I call the Evaluate method to get the result of the expression. Everything works fine. Here is approximately my current situation (Code examples in C#, although this is pretty much language-agnostic):

AST processing and usefulness of visitor pattern

I know the visitor pattern is typically used to traverse a hierarchy of heterogeneous objects (inheriting a same abstract object) and dissociate the processing of these objects from the data within them. A classic use of the visitor pattern (often quoted), is the processing of an abstract syntax tree in a compiler. Indeed, the structure of the tree is only known at runtime (once the program is parsed), and one want to traverse the tree modifying the nodes according to semantic passes implemented as visitor. But the visitor pattern looked like an overkill to me since it allow a double (dynamic) dispatch as a function of the ASTNode type and the Visitor type, or one statically know the order of the visitor we will use to process the AST during the semantic phase. If I had to code this in C++ (done on the spot without compiling), I would do :