#ifndef __AST_HPP__
#define __AST_HPP__

#include <memory>
#include <iostream>
#include <utility>
#include <vector>

#include "symbol.hpp"

class AST {
 public:
  virtual ~AST() = default;
  virtual void sem_analyze() {}
  virtual void compile() const {}
  virtual void printAST(std::ostream &out) const = 0;

 protected:
  void UNREACHABLE() const {
    std::cerr << "Unreachable was reached!" << std::endl;
    std::exit(1);
  }
};

inline std::ostream &operator<<(std::ostream &out, const AST &ast) {
  ast.printAST(out);
  return out;
}

inline std::ostream &operator<<(std::ostream &out, Type t) {
  switch (t) {
    case TYPE_int: out << "int"; break;
    case TYPE_bool: out << "bool"; break;
  }
  return out;
}

class Expr : public AST {
 public:
  void check_type(Type expected_type) {
    sem_analyze();
    if (type != expected_type)
      std::cerr << "Type mismatch" << std::endl;
  }
  virtual int evaluate() const = 0;

 protected:
  Type type;
};

class Stmt : public AST {
 public:
  virtual void execute() const = 0;
};

extern std::vector<int> rt_stack;

class Decl : public AST {
 public:
  Decl(char v, std::unique_ptr<Type> t) : var(v), type(*t) {}

  void sem_analyze() override {
    st.insert(var, type);
  }

  void allocate() {
    rt_stack.push_back(0);
  }

  void deallocate() {
    rt_stack.pop_back();
  }

  void printAST(std::ostream &out) const override {
    out << "Decl(" << var << ":" << type << ")";
  }

 private:
  char var;
  Type type;
};

class BinOp : public Expr {
 public:
  BinOp(std::unique_ptr<Expr> e1, char o, std::unique_ptr<Expr> e2)
    : expr1(std::move(e1)), op(o), expr2(std::move(e2)) {}

  void sem_analyze() override {
    expr1->check_type(TYPE_int);
    expr2->check_type(TYPE_int);
    switch (op) {
      case '+': case '-': case '*': case '/': case '%':
        type = TYPE_int;
        break;
      case '=': case '<': case '>':
        type = TYPE_bool;
        break;
    }
  }

  int evaluate() const override {
    switch (op) {
      case '+': return expr1->evaluate() + expr2->evaluate();
      case '-': return expr1->evaluate() - expr2->evaluate();
      case '*': return expr1->evaluate() * expr2->evaluate();
      case '/': return expr1->evaluate() / expr2->evaluate();
      case '%': return expr1->evaluate() % expr2->evaluate();
      case '=': return expr1->evaluate() == expr2->evaluate();
      case '<': return expr1->evaluate() < expr2->evaluate();
      case '>': return expr1->evaluate() > expr2->evaluate();
    }
    UNREACHABLE(); return 42;
  }

  void compile() const override {
    expr1->compile();
    expr2->compile();
    std::cout << "  popl %ebx" << std::endl   // expr2
              << "  popl %eax" << std::endl;  // expr1
    switch (op) {
      case '+':
        std::cout << "  addl %ebx, %eax" << std::endl
                  << "  pushl %eax"      << std::endl;
        break;
      case '-':
        std::cout << "  subl %ebx, %eax" << std::endl
                  << "  pushl %eax"      << std::endl;
        break;
      case '*':
        std::cout << "  mull %ebx"       << std::endl
                  << "  pushl %eax"      << std::endl;
        break;
      case '/':
        std::cout << "  cbq"             << std::endl
                  << "  divl %ebx"       << std::endl
                  << "  pushl %eax"      << std::endl;
        break;
      case '%':
        std::cout << "  cbq"             << std::endl
                  << "  divl %ebx"       << std::endl
                  << "  pushl %edx"      << std::endl;
        break;
      /*
      case '=': expr1->evaluate() == expr2->evaluate();
      case '<': expr1->evaluate() < expr2->evaluate();
      case '>': expr1->evaluate() > expr2->evaluate();
      */
      default: std::exit(42);
    }
  }

  void printAST(std::ostream &out) const override {
    out << op << "(" << *expr1 << ", " << *expr2 << ")";
  }

 private:
  std::unique_ptr<Expr> expr1;
  char op;
  std::unique_ptr<Expr> expr2;
};

class BoolConst : public Expr {
 public:
  BoolConst(int b) : bv(b) {}

  void sem_analyze() override {
    type = TYPE_bool;
  }

  int evaluate() const override {
    return bv;
  }

  void compile() const override {
    std::cout << "  pushl $" << bv << std::endl;
  }

  void printAST(std::ostream &out) const override {
    out << "BoolConst(" << bv << ")";
  }

 private:
  int bv;
};

class IntConst : public Expr {
 public:
  IntConst(int n) : num(n) {}

  void sem_analyze() override {
    type = TYPE_int;
  }

  int evaluate() const override {
    return num;
  }

  void compile() const override {
    std::cout << "  pushl $" << num << std::endl;
  }

  void printAST(std::ostream &out) const override {
    out << "IntConst(" << num << ")";
  }

 private:
  int num;
};

class Id : public Expr {
 public:
  Id(char v) : var(v) {}
  char name() const { return var; }

  void sem_analyze() override {
    SymTabEntry *e = st.lookup(var);
    type = e->type;
    offset = e->offset;
  }

  int evaluate() const override {
    return rt_stack[offset];
  }

  void compile() const override {
    std::cout << "  pushl " << 4 * (var - 'a') << "(%edi)" << std::endl;
  }

  void printAST(std::ostream &out) const override {
    out << "Id(" << var << ")";
  }

 private:
  char var;
  int offset;
};

class Block : public Stmt {
 public:
  Block() : decl_list(), stmt_list() {}

  void append_decl(std::unique_ptr<Decl> d) {
    decl_list.push_back(std::move(d));
  }

  void append_stmt(std::unique_ptr<Stmt> s) {
    stmt_list.push_back(std::move(s));
  }

  void merge(std::unique_ptr<Block> b) {
    stmt_list = std::move(b->stmt_list);
  }

  void sem_analyze() override {
    st.enter_scope();
    for (const auto &d : decl_list) d->sem_analyze();
    for (const auto &s : stmt_list) s->sem_analyze();
    st.exit_scope();
  }

  void execute() const override {
    for (const auto &decl : decl_list) decl->allocate();
    for (const auto &stmt : stmt_list) stmt->execute();
    for (const auto &decl : decl_list) decl->deallocate();
  }

  void compile() const override {
    for (const auto &stmt : stmt_list) stmt->compile();
  }

  void printAST(std::ostream &out) const override {
    out << "Block(";
    bool first = true;
    for (const auto &d : decl_list) {
      if (!first) out << ", ";
      first = false;
      out << *d;
    }
    for (const auto &s : stmt_list) {
      if (!first) out << ", ";
      first = false;
      out << *s;
    }
    out << ")";
  }

 private:
  std::vector<std::unique_ptr<Decl>> decl_list;
  std::vector<std::unique_ptr<Stmt>> stmt_list;
};

class If : public Stmt {
 public:
  If(std::unique_ptr<Expr> e, std::unique_ptr<Stmt> s1,
     std::unique_ptr<Stmt> s2 = {})
     : expr(std::move(e)), stmt1(std::move(s1)), stmt2(std::move(s2)) {}

  void sem_analyze() override {
    expr->check_type(TYPE_bool);
    stmt1->sem_analyze();
    if (stmt2 != nullptr) stmt2->sem_analyze();
  }

  void execute() const override {
    if (expr->evaluate() != 0)
      stmt1->execute();
    else if (stmt2 != nullptr) stmt2->execute();
  }

  void compile() const override {
    static int counter = 0;
    expr->compile();
    int lelse = counter++;
    std::cout << "  popl %eax"         << std::endl
              << "  andl %eax, %eax"   << std::endl
              << "  jz Lelse" << lelse << std::endl;
    stmt1->compile();
    int lendif = counter++;
    std::cout << "  jmp Lendif" << lendif  << std::endl
              << "Lelse" << lelse << ":"   << std::endl;
    if (stmt2 != nullptr) stmt2->compile();
    std::cout << "Lendif" << lendif << ":" << std::endl;
  }

  void printAST(std::ostream &out) const override {
    out << "If(" << *expr << ", " << *stmt1;
    if (stmt2) out << ", " << *stmt2;
    out << ")";
  }

 private:
  std::unique_ptr<Expr> expr;
  std::unique_ptr<Stmt> stmt1;
  std::unique_ptr<Stmt> stmt2;
};

class For : public Stmt {
 public:
  For(std::unique_ptr<Expr> e, std::unique_ptr<Stmt> s)
    : expr(std::move(e)), stmt(std::move(s)) {}

  void sem_analyze() override {
    expr->check_type(TYPE_int);
    stmt->sem_analyze();
  }

  void execute() const override {
    int limit = expr->evaluate();
    for (int i = 0; i < limit; ++i)
      stmt->execute();
  }

  void compile() const override {
    static int counter = 0;
    expr->compile();
    int lbeg4 = counter++;
    int lend4 = counter++;
    std::cout << "Lbegfor" << lbeg4 << ":" << std::endl
              << "  popl %eax"             << std::endl
              << "  cmp $0, %eax"          << std::endl
              << "  jle Lendfor" << lend4  << std::endl
              << "  decl %eax"             << std::endl
              << "  pushl %eax"            << std::endl;
    stmt->compile();
    std::cout << "  jmp Lbegfor" << lbeg4  << std::endl
              << "Lendfor" << lend4 << ":" << std::endl;
  }

  void printAST(std::ostream &out) const override {
    out << "For(" << *expr << ", " << *stmt << ")";
  }

 private:
  std::unique_ptr<Expr> expr;
  std::unique_ptr<Stmt> stmt;
};

class Let : public Stmt {
 public:
  Let(std::unique_ptr<Id> lhs, std::unique_ptr<Expr> rhs)
    : var(std::move(lhs)), expr(std::move(rhs)) {}

  void sem_analyze() override {
    SymTabEntry *e = st.lookup(var->name());
    expr->check_type(e->type);
    offset = e->offset;
  }

  void execute() const override {
    rt_stack[offset] = expr->evaluate();
  }

  void compile() const override {
    expr->compile();
    std::cout << "  pop %eax" << std::endl
              << "  movl %eax, " << 4 * (var->name() - 'a') << "(%edi)" << std::endl;
  }

  void printAST(std::ostream &out) const override {
    out << "Let(" << *var << ", " << *expr << ")";
  }

 private:
  std::unique_ptr<Id> var;
  std::unique_ptr<Expr> expr;
  int offset;
};

class Print : public Stmt {
 public:
  Print(std::unique_ptr<Expr> e) : expr(std::move(e)) {}

  void sem_analyze() override {
    expr->check_type(TYPE_int);
  }

  void execute() const override {
    std::cout << expr->evaluate() << std::endl;
  }

  void compile() const override {
    expr->compile();
    std::cout << "  popl" << std::endl;
  }

  void printAST(std::ostream &out) const override {
    out << "Print(" << *expr << ")";
  }

 private:
  std::unique_ptr<Expr> expr;
};

inline void prologue() {
  std::cout << ".text"             << std::endl
            << ".global _start"    << std::endl
                                   << std::endl
            << "_start:"           << std::endl
            << "  movl $var, %edi" << std::endl
                                   << std::endl;
}

inline void epilogue() {
  std::cout << ".data"             << std::endl
            << "var:"              << std::endl
            << ".rept 26"          << std::endl
            << ".long 0"           << std::endl
            << ".endr"             << std::endl;
}

#endif
