#include "xyz.h"

#include <algorithm>
#include <climits>

namespace xyz {

namespace {

struct VarInfo {
  TypePtr type;
  bool is_const = false;
};

class Scope {
public:
  Scope() { push(); }

  void push() { scopes_.emplace_back(); }
  void pop() { scopes_.pop_back(); }

  bool declare(const std::string &name, TypePtr type, bool is_const, Pos p) {
    auto &m = scopes_.back();
    if (m.count(name))
      throw Error(p, "duplicate declaration of '" + name + "'");
    m.emplace(name, VarInfo{std::move(type), is_const});
    return true;
  }

  const VarInfo *lookup(const std::string &name) const {
    for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) {
      auto f = it->find(name);
      if (f != it->end())
        return &f->second;
    }
    return nullptr;
  }

private:
  std::vector<std::unordered_map<std::string, VarInfo>> scopes_;
};

class Checker {
public:
  explicit Checker(Program &p) : program_(p) {}

  void run() {
    if (program_.functions.empty())
      throw Error(Pos{}, "program contains no functions");

    for (auto &fn : program_.functions) {
      if (sigs_.count(fn->name))
        throw Error(fn->pos, "duplicate function '" + fn->name + "'");
      FuncSig sig;
      sig.ret = fn->ret;
      for (auto &p : fn->params)
        sig.params.push_back(p.type);
      sigs_.emplace(fn->name, std::move(sig));
    }

    if (!sigs_.count("main"))
      throw Error(Pos{}, "program does not define main");

    for (auto &fn : program_.functions)
      check_function(*fn);
  }

private:
  Program &program_;
  SigMap sigs_;
  Scope *scope_ = nullptr;
  TypePtr current_ret_;
  int loop_depth_ = 0;
  std::string current_fn_;

  static bool printable(const TypePtr &t) {
    return t && (t->kind == Type::Kind::I32 || t->kind == Type::Kind::I64 ||
                 t->kind == Type::Kind::Bool || t->kind == Type::Kind::Str);
  }

  TypePtr unify_int(const TypePtr &a, const TypePtr &b, Pos p) {
    if (!is_int(a) || !is_int(b))
      throw Error(p, "integer operands required");
    return (a->kind == Type::Kind::I64 || b->kind == Type::Kind::I64) ? t_i64()
                                                                     : t_i32();
  }

  void check_function(Function &fn) {
    scope_ = new Scope();
    current_ret_ = fn.ret;
    current_fn_ = fn.name;
    loop_depth_ = 0;

    for (auto &p : fn.params) {
      if (p.type->kind == Type::Kind::Unknown)
        throw Error(p.pos, "unknown type '" + p.type->name + "'");
      if (p.type->kind == Type::Kind::Void)
        throw Error(p.pos, "parameter cannot have type void");
      scope_->declare(p.name, p.type, true, p.pos);
    }

    for (auto &c : fn.contracts) {
      if (c.kind == Contract::Kind::Post && !c.result_name.empty())
        scope_->declare(c.result_name, fn.ret, true, c.pos);
      TypePtr t = check_expr(*c.expr);
      if (t->kind != Type::Kind::Bool)
        throw Error(c.pos, "contract expression must be bool");
    }

    if (fn.arrow) {
      if (fn.ret->kind == Type::Kind::Void)
        throw Error(fn.pos, "expression-bodied function must return a value");
      TypePtr t = check_expr(*fn.arrow);
      if (!assignable(fn.ret, t))
        throw Error(fn.arrow->pos, "function returns " + type_name(t) +
                                       ", expected " + type_name(fn.ret));
    } else if (fn.body) {
      TypePtr last = check_block(*fn.body);
      if (fn.ret->kind != Type::Kind::Void) {
        if (last && last->kind != Type::Kind::Void &&
            assignable(fn.ret, last)) {
          /* The final expression is the implicit return value. */
        } else if (!contains_return(*fn.body)) {
          throw Error(fn.body->pos, "function '" + fn.name + "' can finish "
                                                      "without returning a value");
        }
      }
    } else {
      throw Error(fn.pos, "function has no body");
    }

    delete scope_;
    scope_ = nullptr;
  }

  static bool contains_return(const Block &b) {
    for (auto &s : b.stmts) {
      if (s->kind == Stmt::Kind::Return)
        return true;
      if (s->kind == Stmt::Kind::Expr && s->expr &&
          s->expr->kind == Expr::Kind::If) {
        if (expr_contains_return(*s->expr))
          return true;
      }
      if (s->kind == Stmt::Kind::ForRange || s->kind == Stmt::Kind::ForCond) {
        if (s->block && contains_return(*s->block))
          return true;
      }
      if (s->kind == Stmt::Kind::Block && s->block && contains_return(*s->block))
        return true;
    }
    return false;
  }

  static bool expr_contains_return(const Expr &e) {
    if (e.kind == Expr::Kind::If) {
      if (e.then_e && e.then_e->kind == Expr::Kind::Block && e.then_e->block &&
          contains_return(*e.then_e->block))
        return true;
      if (e.else_e && e.else_e->kind == Expr::Kind::Block && e.else_e->block &&
          contains_return(*e.else_e->block))
        return true;
      if (e.else_e && e.else_e->kind == Expr::Kind::If &&
          expr_contains_return(*e.else_e))
        return true;
    }
    if (e.kind == Expr::Kind::Block && e.block && contains_return(*e.block))
      return true;
    return false;
  }

  TypePtr check_block(Block &b) {
    scope_->push();
    TypePtr last;
    for (auto &s : b.stmts) {
      last = check_stmt(*s);
    }
    scope_->pop();
    return last;
  }

  TypePtr check_stmt(Stmt &s) {
    switch (s.kind) {
    case Stmt::Kind::Let:
    case Stmt::Kind::Var: {
      TypePtr init = check_expr(*s.expr);
      TypePtr t = s.decl_type ? s.decl_type : init;
      if (t->kind == Type::Kind::Unknown)
        throw Error(s.pos, "unknown type '" + t->name + "'");
      if (t->kind == Type::Kind::Void)
        throw Error(s.pos, "variable cannot have type void");
      if (s.decl_type && !assignable(t, init))
        throw Error(s.pos, "cannot initialise " + type_name(t) + " with " +
                               type_name(init));
      scope_->declare(s.name, t, s.kind == Stmt::Kind::Let, s.pos);
      return t_void();
    }
    case Stmt::Kind::Assign: {
      if (s.expr->kind != Expr::Kind::Var)
        throw Error(s.pos, "assignment target must be a variable");
      const VarInfo *v = scope_->lookup(s.expr->text);
      if (!v)
        throw Error(s.pos, "undefined variable '" + s.expr->text + "'");
      if (v->is_const)
        throw Error(s.pos, "cannot assign to '" + s.expr->text + "'");
      s.expr->ty = v->type;
      TypePtr rhs = check_expr(*s.rhs);
      if (s.op == "=") {
        if (!assignable(v->type, rhs))
          throw Error(s.pos, "cannot assign " + type_name(rhs) + " to " +
                                 type_name(v->type));
      } else {
        if (!is_int(v->type) || !is_int(rhs))
          throw Error(s.pos, "compound assignment requires integers");
        if (v->type->kind == Type::Kind::I32 &&
            rhs->kind == Type::Kind::I64)
          throw Error(s.pos, "cannot narrow i64 to i32");
      }
      return t_void();
    }
    case Stmt::Kind::Return: {
      if (s.expr) {
        TypePtr t = check_expr(*s.expr);
        if (current_ret_->kind == Type::Kind::Void)
          throw Error(s.pos, "void function cannot return a value");
        if (!assignable(current_ret_, t))
          throw Error(s.pos, "returning " + type_name(t) + " from function "
                             "returning " + type_name(current_ret_));
      } else if (current_ret_->kind != Type::Kind::Void) {
        throw Error(s.pos, "return value required");
      }
      return t_void();
    }
    case Stmt::Kind::ForRange: {
      TypePtr lo = check_expr(*s.lo);
      TypePtr hi = check_expr(*s.hi);
      TypePtr it = unify_int(lo, hi, s.pos);
      scope_->push();
      scope_->declare(s.name, it, false, s.pos);
      loop_depth_++;
      check_block(*s.block);
      loop_depth_--;
      scope_->pop();
      return t_void();
    }
    case Stmt::Kind::ForCond: {
      TypePtr c = check_expr(*s.cond);
      if (c->kind != Type::Kind::Bool)
        throw Error(s.pos, "for condition must be bool");
      loop_depth_++;
      check_block(*s.block);
      loop_depth_--;
      return t_void();
    }
    case Stmt::Kind::Break:
      if (!loop_depth_)
        throw Error(s.pos, "break outside a loop");
      return t_void();
    case Stmt::Kind::Continue:
      if (!loop_depth_)
        throw Error(s.pos, "continue outside a loop");
      return t_void();
    case Stmt::Kind::Expr:
      check_expr(*s.expr);
      return (s.expr->ty && s.expr->ty->kind != Type::Kind::Void)
                 ? s.expr->ty
                 : t_void();
    case Stmt::Kind::Block:
      return check_block(*s.block);
    }
    return t_void();
  }

  TypePtr check_expr(Expr &e) {
    TypePtr t;
    switch (e.kind) {
    case Expr::Kind::Int:
      if (e.ival >= INT32_MIN && e.ival <= INT32_MAX)
        t = t_i32();
      else
        t = t_i64();
      break;
    case Expr::Kind::Bool:
      t = t_bool();
      break;
    case Expr::Kind::String:
      t = t_str();
      break;
    case Expr::Kind::Var: {
      const VarInfo *v = scope_->lookup(e.text);
      if (!v)
        throw Error(e.pos, "undefined variable '" + e.text + "'");
      t = v->type;
      break;
    }
    case Expr::Kind::Unary: {
      TypePtr a = check_expr(*e.lhs);
      if (e.op == "-") {
        if (!is_int(a))
          throw Error(e.pos, "unary '-' requires an integer");
        t = a;
      } else {
        if (a->kind != Type::Kind::Bool)
          throw Error(e.pos, "unary '!' requires bool");
        t = t_bool();
      }
      break;
    }
    case Expr::Kind::Binary: {
      TypePtr a = check_expr(*e.lhs);
      TypePtr b = check_expr(*e.rhs);
      if (e.op == "+" || e.op == "-" || e.op == "*" || e.op == "/" ||
          e.op == "%") {
        t = unify_int(a, b, e.pos);
      } else if (e.op == "<" || e.op == "<=" || e.op == ">" || e.op == ">=") {
        unify_int(a, b, e.pos);
        t = t_bool();
      } else if (e.op == "==" || e.op == "!=") {
        if (!(is_int(a) && is_int(b)) && !(a->kind == Type::Kind::Bool &&
                                          b->kind == Type::Kind::Bool) &&
            !(a->kind == Type::Kind::Str && b->kind == Type::Kind::Str))
          throw Error(e.pos, "operands are not comparable");
        t = t_bool();
      } else if (e.op == "&&" || e.op == "||") {
        if (a->kind != Type::Kind::Bool || b->kind != Type::Kind::Bool)
          throw Error(e.pos, "logical operands must be bool");
        t = t_bool();
      } else {
        throw Error(e.pos, "unknown operator '" + e.op + "'");
      }
      break;
    }
    case Expr::Kind::Call: {
      if (e.lhs->kind != Expr::Kind::Var)
        throw Error(e.pos, "only named functions can be called");
      const std::string &name = e.lhs->text;
      for (auto &a : e.args)
        check_expr(*a);
      if (name == "print") {
        if (e.args.size() != 1)
          throw Error(e.pos, "print takes exactly one argument");
        if (!printable(e.args[0]->ty))
          throw Error(e.pos, "cannot print " + type_name(e.args[0]->ty));
        t = t_void();
      } else if (name == "__gc_alloc") {
        if (e.args.size() != 1 || !is_int(e.args[0]->ty))
          throw Error(e.pos, "__gc_alloc takes one integer");
        t = t_ptr();
      } else if (name == "__gc_store") {
        if (e.args.size() != 3 || e.args[0]->ty->kind != Type::Kind::Ptr ||
            !is_int(e.args[1]->ty) ||
            e.args[2]->ty->kind != Type::Kind::Ptr)
          throw Error(e.pos, "__gc_store takes (ptr, i32, ptr)");
        t = t_void();
      } else if (name == "__gc_load") {
        if (e.args.size() != 2 || e.args[0]->ty->kind != Type::Kind::Ptr ||
            !is_int(e.args[1]->ty))
          throw Error(e.pos, "__gc_load takes (ptr, i32)");
        t = t_ptr();
      } else if (name == "__gc_alive") {
        if (e.args.size() != 1 || e.args[0]->ty->kind != Type::Kind::Ptr)
          throw Error(e.pos, "__gc_alive takes a ptr");
        t = t_bool();
      } else if (name == "__gc_collect" || name == "__gc_verify") {
        if (!e.args.empty())
          throw Error(e.pos, name + " takes no arguments");
        t = t_void();
      } else if (name == "__gc_pin" || name == "__gc_unpin") {
        if (e.args.size() != 1 || e.args[0]->ty->kind != Type::Kind::Ptr)
          throw Error(e.pos, name + " takes a ptr");
        t = t_void();
      } else {
        auto it = sigs_.find(name);
        if (it == sigs_.end())
          throw Error(e.pos, "unknown function '" + name + "'");
        const FuncSig &sig = it->second;
        if (e.args.size() != sig.params.size())
          throw Error(e.pos, "function '" + name + "' expects " +
                                 std::to_string(sig.params.size()) +
                                 " arguments");
        for (size_t i = 0; i < e.args.size(); i++) {
          if (!assignable(sig.params[i], e.args[i]->ty))
            throw Error(e.args[i]->pos,
                        "argument " + std::to_string(i + 1) + " has type " +
                            type_name(e.args[i]->ty) + ", expected " +
                            type_name(sig.params[i]));
        }
        t = sig.ret;
      }
      break;
    }
    case Expr::Kind::If: {
      TypePtr c = check_expr(*e.cond);
      if (c->kind != Type::Kind::Bool)
        throw Error(e.pos, "if condition must be bool");
      TypePtr a = e.then_e->kind == Expr::Kind::Block
                      ? check_block(*e.then_e->block)
                      : check_expr(*e.then_e);
      TypePtr b = t_void();
      if (e.else_e) {
        b = e.else_e->kind == Expr::Kind::Block ? check_block(*e.else_e->block)
                                                : check_expr(*e.else_e);
      }
      if (!e.else_e) {
        t = t_void();
      } else if (a->kind == Type::Kind::Void && b->kind == Type::Kind::Void) {
        t = t_void();
      } else if (a->kind == Type::Kind::Void || b->kind == Type::Kind::Void) {
        throw Error(e.pos, "both branches of an if expression must produce "
                           "a value");
      } else if (assignable(a, b)) {
        t = a;
      } else if (assignable(b, a)) {
        t = b;
      } else {
        throw Error(e.pos, "if branches have incompatible types " +
                               type_name(a) + " and " + type_name(b));
      }
      break;
    }
    case Expr::Kind::Block:
      t = check_block(*e.block);
      break;
    case Expr::Kind::List:
      throw Error(e.pos,
                  "list expressions are not supported by this milestone");
    case Expr::Kind::Field:
      throw Error(e.pos,
                  "field access is not supported by this milestone");
    case Expr::Kind::Index:
      throw Error(e.pos, "indexing is not supported by this milestone");
    case Expr::Kind::Assign:
      throw Error(e.pos, "assignment is only valid as a statement");
    }
    e.ty = t;
    return t;
  }
};

} // namespace

void check_program(Program &program) {
  Checker c(program);
  c.run();
}

} // namespace xyz
