| Home | Downloads | Documentation | Plugins | Spinoff Projects | Mailing List |
Tutorial 5: Modifying the Traversal Order As explained in the previous tutorials (in particular, Tutorial 1), when a
<?php
if($expr)
{
echo "Do something";
}
else
{
echo "Do something else";
}
?>
is translated to
<?php
if($expr)
{
/* TODO: Insert comment */
echo "Do something";
}
else
{
/* TODO: Insert comment */
echo "Do something else";
}
?>
This appears to be a simple transform. One way to do implement it
would be to introduce a flag However, this will only add a comment to the first statement in
the true branch (try!). To add a comment to the first statement
in the false branch too, we should set the flag to
The Solution For every AST node type xxx, the TreeTransform API defines
a method called
void children_if(AST_if* in)
{
in->expr->visit(this);
in->iftrue->visit(this);
in->iffalse->visit(this);
}
(you can find this definition in generated/Tree_visitor.cpp). If you want to change the order in which the children of a node are visited, entirely avoid visiting some children, or simply execute a piece of code in between two children, this is the method you will need to modify. Here is the transform that does what we need (available as plugins/tutorials/Comment_ifs.so):
class Comment_ifs : public Tree_visitor
{
private:
bool comment;
public:
Comment_ifs()
{
comment = false;
}
void children_if(AST_if* in)
{
in->expr->visit(this);
comment = true;
in->iftrue->visit(this);
comment = true;
in->iffalse->visit(this);
comment = false;
}
void post_statement(AST_statement* in)
{
if(comment && in->get_comments()->empty())
in->get_comments()->push_back(new String("/* TODO: Insert comment */"));
comment = false;
}
};
What's Next?Tutorial 6 explains how to deal with transforms that can replace a single node by multiple new nodes, and shows how to call the phc parser and unparser from your plugins. |
| $LastChangedDate: 2006-09-08 12:24:58 +0100 (Fri, 08 Sep 2006) $. Contents © the authors. |