next up previous
Next: Invoking a Changer Up: Changers Previous: Changer subclass definitions

A Sample Changer

Here is a sample changer that changes all instances of the pre-increment operator (e.g. ++a) to the equivalent assignment:

#include "c_breeze.h"

class preincChanger: public Changer {

        // What to do at a unary node

        Node * at_unary (unaryNode *u, Order) {

                // Is this node doing a preinc?

                if (u->op()->id() == Operator::PREINC) {

                        // Make a node for 'expr + 1'


                        binaryNode * add = new binaryNode ('+',
                                (exprNode *) ref_clone_changer::clone(u->expr(), false),
                                new constNode(1));

                        // Make a node for 'expr = expr + 1'

                        binaryNode *assg = new binaryNode ('=', u->expr(), add);

                        // Return the node

                        return assg;
                }

                // If the node wasn't a preinc, just return it

                return u;
        }

        public:

        preincChanger (void) :
                Changer(Postorder, // visit the tree in postorder (preorder 
                                   // would have worked in this case as well)

                        Subtree,   // descend subtrees

                        false) { } // don't delete the old node; in this case, 
                                   // the old node remains in the tree, it's 
                                   // just placed a little deeper.
};

class preincPhase: public Phase {

public:

preincChanger ic;

void run() {

        unit_list_p u;

        for (u=CBZ::Program.begin(); u!= CBZ::Program.end(); u++) {
                (*u)->change(ic);
        }
}

};

// This line allows you to use the option "-preinc" to invoke
// our phase

Phases Phase("preinc", new preincPhase());



Adam C. Brown 2006-01-26