Pattern 13External Tree Visitor

Purpose

This pattern encapsulates all tree-walking code associated with a particular task into a single visitor class.

Visitors combine tree walking and action execution code outside the AST node definitions. Consequently, we can change the functionality of the tree walker without having to change the AST class definitions and can even switch visitors on the fly. An external visitor can walk either heterogeneous or homogeneous AST nodes.

Discussion

The visitor pattern is the workhorse of choice for tree walking in most language applications. Ultimately you might get tired of manually building visitors, though, and you might come to rely on either Pattern 14, Tree Grammar or Pattern 15, Tree Pattern Matcher

Get Language Implementation Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.