A CIL Tutorial - Department of Computer Science - ETH Zürich
A CIL Tutorial - Department of Computer Science - ETH Zürich
A CIL Tutorial - Department of Computer Science - ETH Zürich
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 2<br />
Visiting the AST<br />
This chapter explains the use <strong>of</strong> the visitor pattern [1] for traversing and modifying the <strong>CIL</strong> AST.<br />
The Visitor pattern dened incil.ml takes care <strong>of</strong> the boilerplate code for traversing the AST,<br />
meaning that we don't have to write a bunch <strong>of</strong> mutually recursive functions every time we want<br />
to walk the AST like we did in Chapter 1.<br />
The visitor pattern in <strong>CIL</strong> uses the O(bjective) features <strong>of</strong> OCaml. We inherit from nopCilVisitor,<br />
which simply walks the AST without doing anything. To do something other than that, we override<br />
the base class's methods.<br />
In this example, we want to pull out assignments to a global variable, which is given as a<br />
parameter to tut2, from a function, which is also given as a parameter to tut2. Thus, we override<br />
the vinst (visit instruction) method.<br />
The result <strong>of</strong> one <strong>of</strong> the methods <strong>of</strong> the visitor class tells the visitor how to proceed next. There<br />
are four options for the result <strong>of</strong> a visitor method:<br />
• SkipChildren Stops the visitor from recursing into child AST nodes<br />
• DoChildren Directs the visitor to recurse into child AST nodes<br />
• ChangeTo x Replaces the AST node with x<br />
• ChangeDoChildrenPost(x, f) Like ChangeTo x, but runs f on the result <strong>of</strong> rebuilding x<br />
with the result <strong>of</strong> the visitor running on x's children.<br />
For ChangeTo x and ChangeDoChildrenPost(x, f), check nopCilVisitor in cil.ml for the correct<br />
types for x and f. Further, note the following important dierence between ChangeTo x and<br />
ChangeDoChildrenPost(x, f): The visitor does not recurse into new nodes added with ChangeTo x.<br />
The visitor does however recurse into new nodes added with ChnageDoChildrenPost(x, f), and<br />
additionally you can give a function(f) to apply to the result.<br />
2.1 tut2.ml<br />
In this module, we will rst subclass <strong>CIL</strong>'s default AST visitor, which simply returns DoChildren<br />
from every method. Then, we'll run the visitor over every function denition in the Cil.file.<br />
16