| Home | Downloads | Documentation | Plugins | Spinoff Projects | Mailing List |
Tutorial 4: Using State This tutorial explains an advanced feature of pattern matching,
and shows an important technique in writing tree transforms: the use
of state. Suppose we are continuing the refactoring tool that we began
in Tutorial 2, and suppose that we have
replaced all calls to database specific functions by calls to the
generic DBX functions. To finish the refactoring, we want to rename
any function So, we want to write a transform that renames all functions
<?php
function first()
{
global $link;
$error = dbx_error($link);
}
function second()
{
echo "Do something else";
}
?>
After the transform, we should get
<?php
function first_DB()
{
global $link;
$error = dbx_error($link);
}
function second()
{
echo "Do something else";
}
?>
The Implementation Since we have to modify method (function) names, the nodes we are
interested in are the nodes of type The solution is in fact very easy. At the start of each method,
we set a variable
class InsertDB : public Tree_visitor
{
private:
int uses_dbx;
public:
void pre_method(AST_method* in)
{
uses_dbx = false;
}
void post_method(AST_method* in)
{
if(uses_dbx)
in->signature->method_name->value->append("_DB");
}
void post_method_invocation(AST_method_invocation* in)
{
Token_method_name* pattern = new Token_method_name(WILDCARD);
// Check for dbx_
if(in->method_name->match(pattern) &&
pattern->value->find("dbx_") == 0)
{
uses_dbx = true;
}
}
};
In Tutorial 2, we simply wanted to
check for a particular function name, and we used
if(in->match(new Token_method_name("mysql_connect")))
Here, we need to check for method names that start with
(Of course, this transform is not complete; renaming methods is not enough, we must also rename the corresponding method invocations. This is left as an exercise for the reader.) What's Next?Tutorial 5 explains how to change the order in which the children of a node are visited, avoid visiting some children, or how to execute a piece of code in between visiting two children. |
| $LastChangedDate: 2006-09-08 12:24:58 +0100 (Fri, 08 Sep 2006) $. Contents © the authors. |