navid/haze / 0609cfc402650382dbc9e0250dd8383dc0f12f15d6d18ea49faba23a8c659c3c / src/sema.cpp

sema.cpp

← src · 31005 bytes · raw · download

#include "haze.h"

#include <algorithm>
#include <climits>

namespace haze {

namespace {

using Subst = std::unordered_map<std::string, const Expr*>;

ExprPtr clone_expr(const Expr& src, const Subst& subst);

ExprPtr clone_var(const std::string& name, const Expr& src, const Subst& subst) {
    auto it = subst.find(name);
    if (it != subst.end()) {
        Subst none;
        return clone_expr(*it->second, none);
    }
    auto e = std::make_unique<Expr>();
    e->kind = Expr::Kind::Var;
    e->pos = src.pos;
    e->ty = src.ty;
    e->text = name;
    return e;
}

BlockPtr clone_block(const Block& src, const Subst& subst);

StmtPtr clone_stmt(const Stmt& src, const Subst& subst) {
    auto s = std::make_unique<Stmt>();
    s->kind = src.kind;
    s->pos = src.pos;
    s->name = src.name;
    s->op = src.op;
    s->decl_type = src.decl_type;
    if (src.expr)
        s->expr = clone_expr(*src.expr, subst);
    if (src.rhs)
        s->rhs = clone_expr(*src.rhs, subst);
    if (src.cond)
        s->cond = clone_expr(*src.cond, subst);
    if (src.lo)
        s->lo = clone_expr(*src.lo, subst);
    if (src.hi)
        s->hi = clone_expr(*src.hi, subst);
    if (src.block)
        s->block = clone_block(*src.block, subst);
    return s;
}

BlockPtr clone_block(const Block& src, const Subst& subst) {
    auto b = std::make_unique<Block>();
    b->pos = src.pos;
    for (auto& s : src.stmts)
        b->stmts.push_back(clone_stmt(*s, subst));
    return b;
}

ExprPtr clone_expr(const Expr& src, const Subst& subst) {
    if (src.kind == Expr::Kind::Var)
        return clone_var(src.text, src, subst);

    auto e = std::make_unique<Expr>();
    e->kind = src.kind;
    e->pos = src.pos;
    e->ty = src.ty;
    e->ival = src.ival;
    e->bval = src.bval;
    e->text = src.text;
    e->op = src.op;
    e->names = src.names;
    if (src.lhs)
        e->lhs = clone_expr(*src.lhs, subst);
    if (src.rhs)
        e->rhs = clone_expr(*src.rhs, subst);
    if (src.cond)
        e->cond = clone_expr(*src.cond, subst);
    if (src.then_e)
        e->then_e = clone_expr(*src.then_e, subst);
    if (src.else_e)
        e->else_e = clone_expr(*src.else_e, subst);
    for (auto& a : src.args)
        e->args.push_back(clone_expr(*a, subst));
    for (auto& arm : src.arms) {
        MatchArm copy;
        copy.pat = arm.pat;
        if (arm.body)
            copy.body = clone_expr(*arm.body, subst);
        e->arms.push_back(std::move(copy));
    }
    if (src.block)
        e->block = clone_block(*src.block, subst);
    return e;
}

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& t : program_.types) {
            if (types_.count(t->name))
                throw Error(Pos{}, "duplicate type '" + t->name + "'");
            types_[t->name] = t;
            if (t->kind == Type::Kind::Record) {
                for (auto& f : t->fields) {
                    validate_type(f.type, f.pos);
                    if (f.type->kind == Type::Kind::Void)
                        throw Error(f.pos, "field cannot have type void");
                }
            } else if (t->kind == Type::Kind::Sum) {
                for (auto& v : t->variants) {
                    for (auto& f : v.fields) {
                        validate_type(f.type, f.pos);
                        if (f.type->kind == Type::Kind::Void)
                            throw Error(f.pos, "field cannot have type void");
                    }
                    if (ctors_.count(v.name))
                        throw Error(v.pos, "duplicate constructor '" + v.name + "'");
                    ctors_[v.name] = CtorInfo{t, &v};
                }
            }
        }

        for (auto& c : program_.contracts) {
            if (contracts_.count(c->name))
                throw Error(c->pos, "duplicate contract '" + c->name + "'");
            contracts_[c->name] = c.get();
            for (auto& p : c->params) {
                validate_type(p.type, p.pos);
                if (p.type->kind == Type::Kind::Void)
                    throw Error(p.pos, "contract parameter cannot have type void");
            }
        }

        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)
            expand_contracts(*fn);

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

private:
    struct CtorInfo {
        TypePtr sum;
        const Variant* variant;
    };

    Program& program_;
    SigMap sigs_;
    std::unordered_map<std::string, TypePtr> types_;
    std::unordered_map<std::string, CtorInfo> ctors_;
    std::unordered_map<std::string, ContractDecl*> contracts_;
    Scope* scope_ = nullptr;
    TypePtr current_ret_;
    int loop_depth_ = 0;
    std::string current_fn_;

    void validate_type(const TypePtr& t, Pos p) {
        if (!t)
            throw Error(p, "missing type");
        if (t->kind == Type::Kind::Unknown)
            throw Error(p, "unknown type '" + t->name + "'");
        if (t->kind == Type::Kind::List)
            validate_type(t->elem, p);
    }

    void expand_contracts(Function& fn) {
        std::vector<Contract> out;
        for (auto& c : fn.contracts) {
            if (c.name.empty()) {
                out.push_back(std::move(c));
                continue;
            }
            auto it = contracts_.find(c.name);
            if (it == contracts_.end())
                throw Error(c.pos, "unknown contract '" + c.name + "'");
            ContractDecl& decl = *it->second;
            if (c.args.size() != decl.params.size())
                throw Error(c.pos, "contract '" + c.name + "' expects " +
                                       std::to_string(decl.params.size()) + " arguments");
            Subst subst;
            for (size_t i = 0; i < decl.params.size(); i++)
                subst[decl.params[i].name] = c.args[i].get();
            for (auto& clause : decl.clauses) {
                Contract nc;
                nc.kind = clause.kind;
                nc.pos = c.pos;
                nc.result_name = clause.result_name;
                nc.expr = clone_expr(*clause.expr, subst);
                out.push_back(std::move(nc));
            }
        }
        fn.contracts = std::move(out);
    }

    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);
        }

        std::unordered_set<std::string> post_names;
        for (auto& c : fn.contracts) {
            if (c.kind == Contract::Kind::Post && !c.result_name.empty() &&
                !post_names.count(c.result_name)) {
                scope_->declare(c.result_name, fn.ret, true, c.pos);
                post_names.insert(c.result_name);
            }
            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::ForIn ||
                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::Match) {
            for (auto& arm : e.arms)
                if (arm.body && arm.body->kind == Expr::Kind::Block && arm.body->block &&
                    contains_return(*arm.body->block))
                    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::ForIn: {
            TypePtr it = check_expr(*s.expr);
            if (it->kind != Type::Kind::List)
                throw Error(s.pos, "for-in requires a list");
            scope_->push();
            scope_->declare(s.name, it->elem, 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) {
                t = v->type;
                break;
            }
            auto c = ctors_.find(e.text);
            if (c == ctors_.end())
                throw Error(e.pos, "undefined variable '" + e.text + "'");
            if (!c->second.variant->fields.empty())
                throw Error(e.pos, "constructor '" + e.text + "' requires arguments");
            t = c->second.sum;
            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);
            auto ctor = ctors_.find(name);
            if (ctor != ctors_.end()) {
                const Variant& v = *ctor->second.variant;
                if (e.args.size() != v.fields.size())
                    throw Error(e.pos, "constructor '" + name + "' expects " +
                                           std::to_string(v.fields.size()) + " arguments");
                for (size_t i = 0; i < e.args.size(); i++) {
                    if (!assignable(v.fields[i].type, 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(v.fields[i].type));
                }
                t = ctor->second.sum;
                break;
            }
            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::Match: {
            TypePtr s = check_expr(*e.lhs);
            if (s->kind != Type::Kind::Sum)
                throw Error(e.pos, "match requires a sum type");
            if (e.arms.empty())
                throw Error(e.pos, "match requires at least one arm");
            TypePtr result = t_void();
            bool have_result = false;
            for (auto& arm : e.arms) {
                scope_->push();
                if (!arm.pat.wildcard) {
                    auto c = ctors_.find(arm.pat.ctor);
                    if (c == ctors_.end())
                        throw Error(arm.pat.pos, "unknown constructor '" + arm.pat.ctor + "'");
                    if (!same_type(s, c->second.sum))
                        throw Error(arm.pat.pos, "pattern '" + arm.pat.ctor +
                                                     "' does not belong to " + type_name(s));
                    const Variant& v = *c->second.variant;
                    if (arm.pat.binders.size() != v.fields.size())
                        throw Error(arm.pat.pos, "pattern '" + arm.pat.ctor + "' expects " +
                                                     std::to_string(v.fields.size()) + " bindings");
                    for (size_t i = 0; i < arm.pat.binders.size(); i++)
                        if (arm.pat.binders[i] != "_")
                            scope_->declare(arm.pat.binders[i], v.fields[i].type, true,
                                            arm.pat.pos);
                }
                TypePtr bt = arm.body->kind == Expr::Kind::Block ? check_block(*arm.body->block)
                                                                 : check_expr(*arm.body);
                scope_->pop();
                if (!have_result) {
                    result = bt;
                    have_result = true;
                } else if (result->kind == Type::Kind::Void && bt->kind == Type::Kind::Void) {
                    /* still void */
                } else if (result->kind == Type::Kind::Void || bt->kind == Type::Kind::Void) {
                    throw Error(arm.body->pos, "all match arms must produce a value or none may");
                } else if (assignable(result, bt)) {
                    /* keep result */
                } else if (assignable(bt, result)) {
                    result = bt;
                } else {
                    throw Error(arm.body->pos, "match arms have incompatible types " +
                                                   type_name(result) + " and " + type_name(bt));
                }
            }
            t = result;
            break;
        }
        case Expr::Kind::Block:
            t = check_block(*e.block);
            break;
        case Expr::Kind::List: {
            if (e.args.empty())
                throw Error(e.pos, "cannot infer the element type of an empty list");
            TypePtr elem = check_expr(*e.args[0]);
            for (size_t i = 1; i < e.args.size(); i++) {
                TypePtr bt = check_expr(*e.args[i]);
                if (is_int(elem) && is_int(bt)) {
                    if (elem->kind == Type::Kind::I64 || bt->kind == Type::Kind::I64)
                        elem = t_i64();
                } else if (assignable(elem, bt)) {
                    /* keep elem */
                } else if (assignable(bt, elem)) {
                    elem = bt;
                } else {
                    throw Error(e.args[i]->pos, "list elements have incompatible types " +
                                                    type_name(elem) + " and " + type_name(bt));
                }
            }
            t = t_list(elem);
            break;
        }
        case Expr::Kind::RecordLit: {
            auto it = types_.find(e.text);
            if (it == types_.end() || it->second->kind != Type::Kind::Record)
                throw Error(e.pos, "unknown record type '" + e.text + "'");
            TypePtr rt = it->second;
            std::unordered_set<std::string> seen;
            for (size_t i = 0; i < e.args.size(); i++) {
                TypePtr at = check_expr(*e.args[i]);
                const Field* field = nullptr;
                for (auto& f : rt->fields)
                    if (f.name == e.names[i])
                        field = &f;
                if (!field)
                    throw Error(e.args[i]->pos,
                                "record '" + e.text + "' has no field '" + e.names[i] + "'");
                if (!seen.insert(e.names[i]).second)
                    throw Error(e.args[i]->pos, "duplicate field '" + e.names[i] + "'");
                if (!assignable(field->type, at))
                    throw Error(e.args[i]->pos, "cannot initialise field '" + e.names[i] +
                                                    "' of type " + type_name(field->type) +
                                                    " with " + type_name(at));
            }
            for (auto& f : rt->fields)
                if (!seen.count(f.name))
                    throw Error(e.pos, "missing field '" + f.name + "' in record literal");
            t = rt;
            break;
        }
        case Expr::Kind::Field: {
            TypePtr base = check_expr(*e.lhs);
            if (base->kind == Type::Kind::List && e.text == "len") {
                t = t_i32();
                break;
            }
            if (base->kind != Type::Kind::Record)
                throw Error(e.pos, "field access requires a record");
            const Field* field = nullptr;
            for (auto& f : base->fields)
                if (f.name == e.text)
                    field = &f;
            if (!field)
                throw Error(e.pos,
                            "record '" + type_name(base) + "' has no field '" + e.text + "'");
            t = field->type;
            break;
        }
        case Expr::Kind::Index: {
            TypePtr base = check_expr(*e.lhs);
            TypePtr idx = check_expr(*e.rhs);
            if (!is_int(idx))
                throw Error(e.rhs->pos, "list index must be an integer");
            if (base->kind != Type::Kind::List)
                throw Error(e.pos, "indexing requires a list");
            t = base->elem;
            break;
        }
        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 haze