Skip to content

Visitor API

Abe Pralle edited this page Nov 26, 2021 · 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 the developer overloads various node handlers to return different nodes - for example, visiting a general Access node may return a specific ReadVar 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_enter(CmdType)
  → on_visit(CmdType)
  → on_visit_children(CmdType)
  → on_leave(CmdType)
enter(Cmd) on_enter(CmdType)
visit_children(Cmd) on_visit_children(CmdType)
leave(Cmd) on_leave(CmdType)

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

Visit Callback Description
on(CmdType)->Cmd If this is overloaded, none of the other callbacks are automatically invoked (on_enter() etc.). Explicitly call visit_children(cmd) if desired. Return null to delete this node from the AST, return cmd to leave it as-is, or return visit(SomeOtherCmdType(...)) to replace this node with a new node. If on(CmdType) is not overloaded then the following four methods will be called in sequence:
on_enter(CmdType) Called before on_visit() (before child nodes are visited).
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.
on_leave(CmdType) Called after on_visit() (after child nodes are visited).

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

Clone this wiki locally