#include "syntree.hpp" #include int counter = 0; InnerNode::InnerNode(Syntree* i1) { _nodes.resize(0); _nodes.push_back(i1); } InnerNode::InnerNode(Syntree* i1, Syntree* i2) { _nodes.resize(0); _nodes.push_back(i1); _nodes.push_back(i2); } InnerNode::InnerNode(Syntree* i1, Syntree* i2, Syntree* i3) { _nodes.resize(0); _nodes.push_back(i1); _nodes.push_back(i2); _nodes.push_back(i3); } InnerNode::~InnerNode() { deinit(); } InnerNode::InnerNode(const InnerNode& i) { init(i); } InnerNode& InnerNode::operator=(const InnerNode& i) { if (this != &i) { deinit(); init(i); } return *this; } void InnerNode::init(const InnerNode& i) { _nodes.resize(0); for (auto n : i._nodes) _nodes.push_back(n->clone()); } void InnerNode::deinit() { for (auto n : _nodes) delete n; } // ---------------- CLONE -------------------- Syntree* Variable::clone() const { return new Variable(*this); } Syntree* Constant::clone() const { return new Constant(*this); } Syntree* Add::clone() const { return new Add(*this); } Syntree* Mul::clone() const { return new Mul(*this); } Syntree* Lt::clone() const { return new Lt(*this); } Syntree* Assign::clone() const { return new Assign(*this); } Syntree* Print::clone() const { return new Print(*this); } Syntree* Seq::clone() const { return new Seq(*this); } Syntree* While::clone() const { return new While(*this); } Syntree* Empty::clone() const { return new Empty(*this); } Syntree* IfThenElse::clone() const { return new IfThenElse(*this); } Syntree* IfThen::clone() const { return new IfThen(*this); } // ---------------- COMPILE ------------------ void Variable::compile() const { cout << "push " << _name << endl; } void Constant::compile() const { cout << "push " << _value << endl; } void Add::compile() const { _nodes[0]->compile(); _nodes[1]->compile(); cout << "add" << endl; } void Mul::compile() const { _nodes[0]->compile(); _nodes[1]->compile(); cout << "mul" << endl; } void Lt::compile() const { _nodes[0]->compile(); _nodes[1]->compile(); cout << "lt" << endl; } void Assign::compile() const { _nodes[1]->compile(); cout << "pop " << ((Variable*)_nodes[0])->getName() << endl; } void Print::compile() const { _nodes[0]->compile(); cout << "print" << endl; } void Seq::compile() const { for (auto n : _nodes) n->compile(); } void While::compile() const { int tmp = counter; counter += 2; cout << "L" << tmp++ << ":" << endl; _nodes[0]->compile(); cout << "jz L" << tmp << endl; _nodes[1]->compile(); cout << "jmp L" << tmp-1 << endl; cout << "L" << tmp << ":" << endl; } void Empty::compile() const { } void IfThenElse::compile() const { int tmp = counter; counter += 2; _nodes[0]->compile(); cout << "jz L" << tmp << endl; _nodes[1]->compile(); cout << "jmp L" << tmp+1 << endl; cout << "L" << tmp++ << ":" << endl; _nodes[2]->compile(); cout << "L" << tmp << ":" << endl; } void IfThen::compile() const { int tmp = counter; counter += 1; _nodes[0]->compile(); cout << "jz L" << tmp << endl; _nodes[1]->compile(); cout << "L" << tmp << ":" << endl; }