// Access to C-Breeze functionality is in "c_breeze.h" #include "c_breeze.h" // This Walker counts assignments class CountAssg: public Walker { int _assgcount; // keep count of the assignments public: CountAssg (void): // constructor // we will walk the tree in preorder, visiting subtrees Walker (Preorder, Subtree), // initially the count is zero _assgcount(0) {} // override at_binary() of Walker // this function is called on every node representing a // binary operator. 'ord' tells us in what order the AST // is being visited, Preorder or Postorder; we don't need it yet. // binaryNode is a subclass of Node, a general AST node type. void at_binary (binaryNode *n, Order ord) { // if this binaryNode is an assignment, increment the count if (n->op()->is_assignment()) _assgcount++; } // return the number of assignments counted int assgcount(void) { return _assgcount; } }; // This phase runs the CountAssg Walker on each translation unit. class CountAssgPhase: public Phase { public: CountAssg cw; // an instance of the CountAssg Walker void run (void) { // an iterator through a list of translation units unit_list_p u; // for each translation unit in the program... for (u=CBZ::Program.begin(); u!= CBZ::Program.end(); u++) // ... walk the AST using the CountAssg walker (*u)->walk (cw); // print the result to standard output cout << "number of assignments: " << cw.assgcount() << '\n'; } }; // This line causes C-Breeze to "see" the new Phase. We name it "countassg" // so that when we run C-Breeze from the command line, giving the option // "-countassg" will invoke our phase. Phases Phase ("countassg", new CountAssgPhase());
This code is pretty standard for a C-Breeze walker; you can customize it yourself to do many different things. If you're bothered by some of the conventions, don't worry. What's really important is the code in the CountId class; the rest is just stuff to make it go.