#include "xyz.h"

#include <utility>

namespace xyz {

namespace {

class Parser {
public:
  explicit Parser(std::vector<Token> tokens) : tokens_(std::move(tokens)) {}

  Program program() {
    Program p;
    while (!at(Tok::End)) {
      bool pure = false;
      bool pub = false;
      for (;;) {
        if (is_ident("pure")) {
          pure = true;
          advance();
        } else if (is_ident("pub")) {
          pub = true;
          advance();
        } else {
          break;
        }
      }
      if (is_ident("fn")) {
        p.functions.push_back(parse_fn(pure, pub));
        continue;
      }
      if (is_ident("type") || is_ident("contract") || is_ident("interface") ||
          is_ident("trait") || is_ident("impl") || is_ident("use") ||
          is_ident("import"))
        throw Error(cur().pos,
                    "'" + cur().text +
                        "' declarations are not supported by this milestone");
      throw Error(cur().pos, "expected 'fn' at top level");
    }
    return p;
  }

private:
  std::vector<Token> tokens_;
  size_t i_ = 0;

  const Token &cur() const { return tokens_[i_]; }
  const Token &at(size_t n) const {
    size_t k = i_ + n;
    return k < tokens_.size() ? tokens_[k] : tokens_.back();
  }
  void advance() {
    if (i_ + 1 < tokens_.size())
      i_++;
  }
  bool at(Tok k) const { return cur().kind == k; }
  bool is_ident(const std::string &s) const {
    return cur().kind == Tok::Ident && cur().text == s;
  }
  bool match(Tok k) {
    if (!at(k))
      return false;
    advance();
    return true;
  }
  bool match_ident(const std::string &s) {
    if (!is_ident(s))
      return false;
    advance();
    return true;
  }
  Token expect(Tok k, const std::string &what) {
    if (!at(k))
      throw Error(cur().pos, "expected " + what);
    Token t = cur();
    advance();
    return t;
  }
  std::string expect_ident(const std::string &what = "identifier") {
    if (cur().kind != Tok::Ident)
      throw Error(cur().pos, "expected " + what);
    std::string s = cur().text;
    advance();
    return s;
  }

  TypePtr parse_type() {
    if (cur().kind != Tok::Ident)
      throw Error(cur().pos, "expected a type");
    std::string name = cur().text;
    Pos p = cur().pos;
    advance();
    if (name == "i32")
      return t_i32();
    if (name == "i64")
      return t_i64();
    if (name == "bool")
      return t_bool();
    if (name == "str")
      return t_str();
    if (name == "ptr")
      return t_ptr();
    if (name == "void")
      return t_void();
    if (name == "list") {
      expect(Tok::LBracket, "'[' after list");
      TypePtr elem = parse_type();
      expect(Tok::RBracket, "']' after list element type");
      return t_list(std::move(elem));
    }
    if (name == "fn") {
      (void)p;
      throw Error(p, "function types are not supported by this milestone");
    }
    return t_unknown(name);
  }

  ExprPtr make_block_expr(BlockPtr b, Pos p) {
    auto e = std::make_unique<Expr>();
    e->kind = Expr::Kind::Block;
    e->pos = p;
    e->block = std::move(b);
    return e;
  }

  BlockPtr parse_block() {
    Pos p = cur().pos;
    expect(Tok::LBrace, "'{'");
    auto b = std::make_unique<Block>();
    b->pos = p;
    while (!at(Tok::RBrace)) {
      if (at(Tok::End))
        throw Error(cur().pos, "unterminated block");
      b->stmts.push_back(parse_stmt());
    }
    expect(Tok::RBrace, "'}'");
    return b;
  }

  StmtPtr parse_stmt() {
    Pos p = cur().pos;

    if (match_ident("const") || match_ident("var")) {
      bool is_const = tokens_[i_ - 1].text == "const";
      auto s = std::make_unique<Stmt>();
      s->kind = is_const ? Stmt::Kind::Let : Stmt::Kind::Var;
      s->pos = p;
      s->name = expect_ident("variable name");
      if (match(Tok::Colon))
        s->decl_type = parse_type();
      expect(Tok::Assign, "'=' in variable declaration");
      s->expr = parse_expr();
      return s;
    }

    if (match_ident("return")) {
      auto s = std::make_unique<Stmt>();
      s->kind = Stmt::Kind::Return;
      s->pos = p;
      if (!at(Tok::RBrace) && !at(Tok::End))
        s->expr = parse_expr();
      return s;
    }

    if (match_ident("for")) {
      auto s = std::make_unique<Stmt>();
      s->pos = p;
      if (cur().kind == Tok::Ident && at(1).kind == Tok::Ident &&
          at(1).text == "in") {
        s->kind = Stmt::Kind::ForRange;
        s->name = cur().text;
        advance();
        advance();
        s->lo = parse_expr();
        expect(Tok::DotDot, "'..' in for range");
        s->hi = parse_expr();
        s->block = parse_block();
        return s;
      }
      s->kind = Stmt::Kind::ForCond;
      s->cond = parse_expr();
      s->block = parse_block();
      return s;
    }

    if (match_ident("break")) {
      auto s = std::make_unique<Stmt>();
      s->kind = Stmt::Kind::Break;
      s->pos = p;
      return s;
    }
    if (match_ident("continue")) {
      auto s = std::make_unique<Stmt>();
      s->kind = Stmt::Kind::Continue;
      s->pos = p;
      return s;
    }

    if (at(Tok::LBrace)) {
      auto s = std::make_unique<Stmt>();
      s->kind = Stmt::Kind::Block;
      s->pos = p;
      s->block = parse_block();
      return s;
    }

    ExprPtr lhs = parse_expr();
    if (at(Tok::Assign) || at(Tok::PlusEq) || at(Tok::MinusEq) ||
        at(Tok::StarEq) || at(Tok::SlashEq) || at(Tok::PercentEq)) {
      auto s = std::make_unique<Stmt>();
      s->kind = Stmt::Kind::Assign;
      s->pos = p;
      switch (cur().kind) {
      case Tok::Assign:
        s->op = "=";
        break;
      case Tok::PlusEq:
        s->op = "+=";
        break;
      case Tok::MinusEq:
        s->op = "-=";
        break;
      case Tok::StarEq:
        s->op = "*=";
        break;
      case Tok::SlashEq:
        s->op = "/=";
        break;
      default:
        s->op = "%=";
        break;
      }
      advance();
      s->expr = std::move(lhs);
      s->rhs = parse_expr();
      return s;
    }
    if (at(Tok::PlusPlus) || at(Tok::MinusMinus)) {
      bool inc = at(Tok::PlusPlus);
      advance();
      auto one = std::make_unique<Expr>();
      one->kind = Expr::Kind::Int;
      one->pos = p;
      one->ival = 1;
      one->ty = t_i32();
      auto s = std::make_unique<Stmt>();
      s->kind = Stmt::Kind::Assign;
      s->pos = p;
      s->op = inc ? "+=" : "-=";
      s->expr = std::move(lhs);
      s->rhs = std::move(one);
      return s;
    }

    auto s = std::make_unique<Stmt>();
    s->kind = Stmt::Kind::Expr;
    s->pos = p;
    s->expr = std::move(lhs);
    return s;
  }

  std::unique_ptr<Function> parse_fn(bool pure, bool pub) {
    Pos p = cur().pos;
    expect_ident("fn");
    auto fn = std::make_unique<Function>();
    fn->pos = p;
    fn->pure = pure;
    fn->pub = pub;
    fn->name = expect_ident("function name");

    if (match(Tok::LBracket)) {
      int depth = 1;
      while (depth > 0) {
        if (at(Tok::End))
          throw Error(cur().pos, "unterminated generic parameter list");
        if (at(Tok::LBracket))
          depth++;
        else if (at(Tok::RBracket))
          depth--;
        advance();
      }
    }

    expect(Tok::LParen, "'(' after function name");
    while (!at(Tok::RParen)) {
      Param param;
      param.pos = cur().pos;
      param.name = expect_ident("parameter name");
      param.type = parse_type();
      fn->params.push_back(std::move(param));
      if (!match(Tok::Comma))
        break;
    }
    expect(Tok::RParen, "')' after parameters");

    if (!at(Tok::Arrow) && !at(Tok::LBrace) && !at(Tok::Colon))
      fn->ret = parse_type();
    else
      fn->ret = t_void();

    while (match(Tok::Colon)) {
      if (match_ident("pre")) {
        Contract c;
        c.kind = Contract::Kind::Pre;
        c.pos = p;
        c.expr = parse_expr();
        fn->contracts.push_back(std::move(c));
      } else if (match_ident("post")) {
        Contract c;
        c.kind = Contract::Kind::Post;
        c.pos = p;
        if (cur().kind == Tok::Ident)
          c.result_name = cur().text;
        if (c.result_name.size() && at(1).kind == Tok::Arrow) {
          advance();
          advance();
        }
        c.expr = parse_expr();
        fn->contracts.push_back(std::move(c));
      } else {
        throw Error(cur().pos,
                    "named contracts are not supported by this milestone");
      }
    }

    if (match(Tok::Arrow)) {
      fn->arrow = parse_expr();
    } else {
      fn->body = parse_block();
    }
    return fn;
  }

  std::vector<ExprPtr> parse_args() {
    std::vector<ExprPtr> args;
    expect(Tok::LParen, "'('");
    while (!at(Tok::RParen)) {
      args.push_back(parse_expr());
      if (!match(Tok::Comma))
        break;
    }
    expect(Tok::RParen, "')' after arguments");
    return args;
  }

  ExprPtr parse_if_expr() {
    Pos p = cur().pos;
    expect_ident("if");
    auto e = std::make_unique<Expr>();
    e->kind = Expr::Kind::If;
    e->pos = p;
    e->cond = parse_expr();
    e->then_e = make_block_expr(parse_block(), p);
    if (match_ident("else")) {
      if (is_ident("if")) {
        e->else_e = parse_if_expr();
      } else {
        e->else_e = make_block_expr(parse_block(), p);
      }
    }
    return e;
  }

  ExprPtr parse_primary() {
    Pos p = cur().pos;
    if (at(Tok::Int)) {
      auto e = std::make_unique<Expr>();
      e->kind = Expr::Kind::Int;
      e->pos = p;
      e->ival = cur().ival;
      advance();
      return e;
    }
    if (at(Tok::Str)) {
      auto e = std::make_unique<Expr>();
      e->kind = Expr::Kind::String;
      e->pos = p;
      e->text = cur().text;
      advance();
      return e;
    }
    if (at(Tok::Ident)) {
      if (is_ident("true") || is_ident("false")) {
        auto e = std::make_unique<Expr>();
        e->kind = Expr::Kind::Bool;
        e->pos = p;
        e->bval = is_ident("true");
        advance();
        return e;
      }
      if (is_ident("if"))
        return parse_if_expr();
      auto e = std::make_unique<Expr>();
      e->kind = Expr::Kind::Var;
      e->pos = p;
      e->text = cur().text;
      advance();
      return e;
    }
    if (match(Tok::LParen)) {
      ExprPtr e = parse_expr();
      expect(Tok::RParen, "')'");
      return e;
    }
    if (at(Tok::LBrace)) {
      return make_block_expr(parse_block(), p);
    }
    if (match(Tok::LBracket)) {
      auto e = std::make_unique<Expr>();
      e->kind = Expr::Kind::List;
      e->pos = p;
      while (!at(Tok::RBracket)) {
        e->args.push_back(parse_expr());
        if (!match(Tok::Comma))
          break;
      }
      expect(Tok::RBracket, "']' after list literal");
      return e;
    }
    throw Error(cur().pos, "expected an expression");
  }

  ExprPtr parse_postfix() {
    ExprPtr e = parse_primary();
    for (;;) {
      if (at(Tok::LParen)) {
        auto call = std::make_unique<Expr>();
        call->kind = Expr::Kind::Call;
        call->pos = e->pos;
        call->lhs = std::move(e);
        call->args = parse_args();
        e = std::move(call);
        continue;
      }
      if (match(Tok::Dot)) {
        auto field = std::make_unique<Expr>();
        field->kind = Expr::Kind::Field;
        field->pos = e->pos;
        field->text = expect_ident("field name");
        field->lhs = std::move(e);
        e = std::move(field);
        continue;
      }
      if (match(Tok::LBracket)) {
        auto index = std::make_unique<Expr>();
        index->kind = Expr::Kind::Index;
        index->pos = e->pos;
        index->lhs = std::move(e);
        index->rhs = parse_expr();
        expect(Tok::RBracket, "']' after index");
        e = std::move(index);
        continue;
      }
      break;
    }
    return e;
  }

  ExprPtr parse_unary() {
    if (at(Tok::Minus) || at(Tok::Bang)) {
      Pos p = cur().pos;
      std::string op = at(Tok::Minus) ? "-" : "!";
      advance();
      auto e = std::make_unique<Expr>();
      e->kind = Expr::Kind::Unary;
      e->pos = p;
      e->op = op;
      e->lhs = parse_unary();
      return e;
    }
    return parse_postfix();
  }

  ExprPtr make_binary(std::string op, ExprPtr l, ExprPtr r, Pos p) {
    auto e = std::make_unique<Expr>();
    e->kind = Expr::Kind::Binary;
    e->pos = p;
    e->op = std::move(op);
    e->lhs = std::move(l);
    e->rhs = std::move(r);
    return e;
  }

  ExprPtr parse_multiplicative() {
    ExprPtr l = parse_unary();
    while (at(Tok::Star) || at(Tok::Slash) || at(Tok::Percent)) {
      Pos p = cur().pos;
      std::string op = at(Tok::Star) ? "*" : (at(Tok::Slash) ? "/" : "%");
      advance();
      l = make_binary(op, std::move(l), parse_unary(), p);
    }
    return l;
  }

  ExprPtr parse_additive() {
    ExprPtr l = parse_multiplicative();
    while (at(Tok::Plus) || at(Tok::Minus)) {
      Pos p = cur().pos;
      std::string op = at(Tok::Plus) ? "+" : "-";
      advance();
      l = make_binary(op, std::move(l), parse_multiplicative(), p);
    }
    return l;
  }

  ExprPtr parse_comparison() {
    ExprPtr l = parse_additive();
    while (at(Tok::Lt) || at(Tok::Le) || at(Tok::Gt) || at(Tok::Ge)) {
      Pos p = cur().pos;
      std::string op;
      switch (cur().kind) {
      case Tok::Lt:
        op = "<";
        break;
      case Tok::Le:
        op = "<=";
        break;
      case Tok::Gt:
        op = ">";
        break;
      default:
        op = ">=";
        break;
      }
      advance();
      l = make_binary(op, std::move(l), parse_additive(), p);
    }
    return l;
  }

  ExprPtr parse_equality() {
    ExprPtr l = parse_comparison();
    while (at(Tok::EqEq) || at(Tok::NotEq)) {
      Pos p = cur().pos;
      std::string op = at(Tok::EqEq) ? "==" : "!=";
      advance();
      l = make_binary(op, std::move(l), parse_comparison(), p);
    }
    return l;
  }

  ExprPtr parse_and() {
    ExprPtr l = parse_equality();
    while (at(Tok::AndAnd)) {
      Pos p = cur().pos;
      advance();
      l = make_binary("&&", std::move(l), parse_equality(), p);
    }
    return l;
  }

  ExprPtr parse_or() {
    ExprPtr l = parse_and();
    while (at(Tok::OrOr)) {
      Pos p = cur().pos;
      advance();
      l = make_binary("||", std::move(l), parse_and(), p);
    }
    return l;
  }

  ExprPtr parse_expr() { return parse_or(); }
};

} // namespace

Program parse_program(const std::string &src) {
  Parser p(lex(src));
  return p.program();
}

} // namespace xyz
