#include #include #include using namespace std; // C++ rule: // No object may be created if any of its methods are // pure virtual (abstract) // so in our case the =NULL notation to make node's methods // pure virtual is more trouble than it's worth. struct node { virtual string kind() { return "generic"; } virtual int get_value() { cout << "Error 1\n"; exit(1); } virtual node * get_pointer(int n) { cout << "Error 2\n"; exit(1); } virtual string get_name() { cout << "Error 3\n"; exit(1); } virtual string get_operator() { cout << "Error 4\n"; exit(1); } virtual void print(int indent) { cout << "generic"; } }; int lookupinsymboltable(string name) { if (name=="cat") return 100; if (name=="bat") return 32; if (name=="hat") return 3; cout << "unknown variable " << name << "\n"; return 0; } void print_spaces(int n) { for (int i=0; i=nptrs) return NULL; return pointers[i]; } }; struct arith_node: public node_with_ptrs { string op; arith_node(node * a, string o, node * b) { op=o; add_pointer(a); add_pointer(b); } virtual void print(int indent) { cout << "("; get_pointer(0)->print(indent+1); cout << op; get_pointer(1)->print(indent+1); cout << ")"; } virtual int get_value() { int a = get_pointer(0)->get_value(); int b = get_pointer(1)->get_value(); if (op=="+") return a+b; else if (op=="-") return a-b; else if (op=="*") return a*b; else if (op=="/") return a/b; else if (op==">") return a>b; else cout << "error"; } virtual string kind() { return "arithmetic"; } virtual string get_operator() { return op; } }; struct if_node: public node_with_ptrs { if_node(node * cond, node * truep, node * falsep = NULL) { add_pointer(cond); add_pointer(truep); if (falsep!=NULL) add_pointer(falsep); } virtual string kind() { return "if"; } virtual int get_value() { int cond = get_pointer(0)->get_value(); if (cond!=0) return get_pointer(1)->get_value(); else if (how_many_ptrs()==3) return get_pointer(2)->get_value(); else return 0; } virtual void print(int indent) { cout << "if "; get_pointer(0)->print(indent+1); cout << "\n"; print_spaces(indent+1); get_pointer(1)->print(indent+1); if (how_many_ptrs()==3) { cout << "\n"; print_spaces(indent); cout << "else\n"; print_spaces(indent+1); get_pointer(2)->print(indent+1); } } }; void test(node * p) { cout << "-------------------testing----------------------\n"; p->print(0); cout << "\n\nvalue is " << p->get_value(); cout << "\n------------------------------------------------\n"; } void main() { test(new var_node("cat")); test(new var_node("bat")); test(new var_node("hat")); test( new if_node( new arith_node( new var_node("cat"), ">", new number_node(7)), new if_node( new arith_node( new var_node("hat"), ">", new number_node(2)), new number_node(13), new arith_node( new var_node("bat"), "-", new number_node(27))), new arith_node( new arith_node( new var_node("cat"), "*", new var_node("bat")), "+", new arith_node( new var_node("hat"), "*", new number_node(1))))); }