Skip to content

Visitor API

Abe Pralle edited this page Jan 16, 2022 · 11 revisions

Base class Visitor uses a sophisticated multi-tiered double dispatch system (polymorphic callbacks). By default an extended Visitor will visit each node in an AST, rebuilding the AST by reassigning each child to be the node resulting from visiting the child. The rebuilt AST will be the same unless you overload various node handlers to return different nodes - for example, you may define the on() for a general Access node to return a resolved GetVar node instead.

Due to the double dispatch system, the visitor methods you call are not the same as the methods you overload to change behavior. The table below shows the mapping.

Method Call Called Methods
visit(Cmd)->Cmd on(CmdType)->Cmd
→ on_visit(CmdType)
     → on_visit_children(CmdType)
handle_visit(Cmd)->Cmd on_visit(CmdType)
→ on_visit_children(CmdType)
visit_children(Cmd) on_visit_children(CmdType)

Here is a table describing the overloadable callbacks in more detail.

Visit Callback Description
on(CmdType)->Cmd If this is overloaded, on_visit() and on_visit_children() are not automatically invoked. If desired, explicitly call handle_visit(cmd) (which calls visit_children(cmd) by default) or just visit_children(cmd). Return null to delete this node from the AST, return cmd to leave it as-is, or return a new or different Cmd node to replace this node. If on(CmdType) is not overloaded then the following two methods will be called in sequence:
on_visit(CmdType) Overload this to prevent child nodes from being automatically visited. Explicitly call visit_children(cmd) if and when you want to visit child nodes.
on_visit_children(CmdType) Overload/overide this to define how child nodes are visited for a given node type.

In extended Visitor classes you only need to overload the node types you want to add custom logic to.

Clone this wiki locally