navid/haze / ea08ceb46539df9cf3ac396bc0bd66fc4f6b9adc630e1596e79b8e4d3101673a / src/parser.cpp

parser.cpp

← src · 40674 bytes · raw · download

#include "haze.h"

#include <cctype>
#include <utility>

namespace haze {

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")) {
                p.types.push_back(parse_type_decl(pub));
                continue;
            }
            if (is_ident("const")) {
                if (pure)
                    throw Error(cur().pos, "'pure' is only valid on functions");
                p.globals.push_back(parse_global(pub));
                continue;
            }
            if (pure)
                throw Error(cur().pos, "expected 'fn' after modifier");
            if (is_ident("contract")) {
                p.contracts.push_back(parse_contract_decl(pub));
                continue;
            }
            if (is_ident("use")) {
                p.uses.push_back(parse_use());
                continue;
            }
            if (is_ident("interface") || is_ident("trait") || is_ident("impl") ||
                is_ident("import"))
                throw Error(cur().pos, "'" + cur().text +
                                           "' declarations are not supported by this milestone");
            throw Error(cur().pos, "expected 'fn', 'type', 'const', 'contract', or 'use' at top level");
        }
        return p;
    }

private:
    static constexpr size_t kNoLimit = static_cast<size_t>(-1);

    std::vector<Token> tokens_;
    size_t i_ = 0;
    size_t limit_ = kNoLimit;
    std::unordered_map<std::string, TypePtr> named_types_;
    std::unordered_set<std::string> type_params_;
    std::unordered_set<std::string> imported_names_;

    const Token& cur() const {
        return i_ < limit_ ? tokens_[i_] : tokens_.back();
    }
    const Token& at(size_t n) const {
        size_t k = i_ + n;
        if (k >= limit_)
            return tokens_.back();
        return k < tokens_.size() ? tokens_[k] : tokens_.back();
    }
    void advance() {
        if (i_ + 1 < tokens_.size() && i_ + 1 <= limit_)
            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 == "i8")
            return t_i8();
        if (name == "i16")
            return t_i16();
        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 == "option" || name == "Option") {
            expect(Tok::LBracket, "'[' after Option");
            TypePtr elem = parse_type();
            expect(Tok::RBracket, "']' after Option element type");
            return t_option(std::move(elem));
        }
        if (name == "result" || name == "Result") {
            expect(Tok::LBracket, "'[' after Result");
            TypePtr ok = parse_type();
            expect(Tok::Comma, "',' between Result types");
            TypePtr err = parse_type();
            expect(Tok::RBracket, "']' after Result types");
            return t_result(std::move(ok), std::move(err));
        }
        if (name == "fn") {
            expect(Tok::LParen, "'(' in function type");
            std::vector<TypePtr> params;
            while (!at(Tok::RParen)) {
                params.push_back(parse_type());
                if (!match(Tok::Comma))
                    break;
            }
            expect(Tok::RParen, "')' after function type parameters");
            TypePtr ret = (at(Tok::Arrow) || at(Tok::LBrace) || at(Tok::Comma) ||
                           at(Tok::RParen) || at(Tok::RBracket) || at(Tok::End))
                              ? t_void()
                              : parse_type();
            return t_function(std::move(params), std::move(ret));
        }
        if (match(Tok::LBracket)) {
            std::vector<TypePtr> args;
            while (!at(Tok::RBracket)) {
                args.push_back(parse_type());
                if (!match(Tok::Comma))
                    break;
            }
            expect(Tok::RBracket, "']' after type arguments");
            auto ref = t_generic_ref(name, std::move(args));
            auto known = named_types_.find(name);
            if (known != named_types_.end())
                ref->base = known->second;
            return ref;
        }
        if (type_params_.count(name))
            return t_param(name);
        auto it = named_types_.find(name);
        if (it != named_types_.end())
            return it->second;
        return t_unknown(name);
    }

    TypePtr parse_type_decl(bool pub) {
        Pos p = cur().pos;
        expect_ident("type");
        std::string name = expect_ident("type name");
        if (named_types_.count(name))
            throw Error(p, "duplicate type '" + name + "'");

        std::vector<std::string> generic_params;
        if (match(Tok::LBracket)) {
            while (!at(Tok::RBracket)) {
                if (at(Tok::End))
                    throw Error(cur().pos, "unterminated generic parameter list");
                std::string param = expect_ident("type parameter name");
                if (param == "i8" || param == "i16" || param == "i32" || param == "i64" ||
                    param == "bool" || param == "str" || param == "ptr" ||
                    param == "void" || param == "list" || param == "option" ||
                    param == "Option" || param == "result" || param == "Result" ||
                    param == "fn")
                    throw Error(cur().pos, "type parameter name '" + param +
                                               "' shadows a builtin type");
                for (auto& existing : generic_params)
                    if (existing == param)
                        throw Error(cur().pos, "duplicate type parameter '" + param + "'");
                generic_params.push_back(param);
                if (!match(Tok::Comma))
                    break;
            }
            expect(Tok::RBracket, "']' after type parameters");
        }

        auto saved_type_params = type_params_;
        for (auto& param : generic_params)
            type_params_.insert(param);
        auto restore = [&]() { type_params_ = saved_type_params; };

        if (is_ident("enum")) {
            if (!generic_params.empty()) {
                restore();
                throw Error(cur().pos, "enum types cannot declare type parameters");
            }
            advance();
            auto t = t_enum(name);
            t->pub = pub;
            t->type_params = generic_params;
            named_types_[name] = t;
            expect(Tok::LBrace, "'{' in enum declaration");
            while (!at(Tok::RBrace)) {
                if (at(Tok::End)) {
                    restore();
                    throw Error(cur().pos, "unterminated enum declaration");
                }
                Variant v;
                v.pos = cur().pos;
                v.name = expect_ident("enum variant");
                t->variants.push_back(std::move(v));
                match(Tok::Comma);
            }
            expect(Tok::RBrace, "'}' after enum variants");
            restore();
            return t;
        }

        bool is_sum = match(Tok::Assign);
        if (!is_sum && at(Tok::Pipe))
            is_sum = true;
        if (!is_sum && !at(Tok::LBrace) && !at(Tok::Pipe)) {
            restore();
            throw Error(cur().pos, "expected '{' or '=' after type name");
        }

        TypePtr t = is_sum ? t_sum(name) : t_record(name);
        t->pub = pub;
        t->type_params = generic_params;
        named_types_[name] = t;

        if (is_sum) {
            if (!at(Tok::Pipe)) {
                restore();
                throw Error(cur().pos, "expected '|' in sum type declaration");
            }
            while (match(Tok::Pipe)) {
                Variant v;
                v.pos = cur().pos;
                v.name = expect_ident("variant name");
                if (match(Tok::LParen)) {
                    while (!at(Tok::RParen)) {
                        Field f;
                        f.pos = cur().pos;
                        f.name = expect_ident("field name");
                        f.type = parse_type();
                        v.fields.push_back(std::move(f));
                        if (!match(Tok::Comma))
                            break;
                    }
                    expect(Tok::RParen, "')' after variant fields");
                }
                t->variants.push_back(std::move(v));
            }
            restore();
            return t;
        }

        expect(Tok::LBrace, "'{' in record declaration");
        while (!at(Tok::RBrace)) {
            if (at(Tok::End)) {
                restore();
                throw Error(cur().pos, "unterminated type declaration");
            }
            Field f;
            f.pos = cur().pos;
            f.name = expect_ident("field name");
            f.type = parse_type();
            t->fields.push_back(std::move(f));
            match(Tok::Comma);
        }
        expect(Tok::RBrace, "'}' after record fields");
        restore();
        return t;
    }

    Global parse_global(bool pub) {
        Pos p = cur().pos;
        expect_ident("const");
        Global g;
        g.pos = p;
        g.pub = pub;
        g.name = expect_ident("constant name");
        if (!at(Tok::Assign))
            g.type = parse_type();
        expect(Tok::Assign, "'=' in constant declaration");
        g.expr = parse_expr();
        return g;
    }

    Use parse_use() {
        Pos p = cur().pos;
        expect_ident("use");
        Use u;
        u.pos = p;
        if (at(Tok::DotDot)) {
            u.module = "..";
            advance();
        } else if (match(Tok::Dot)) {
            u.module = ".";
        } else {
            u.module = expect_ident("module name");
        }
        while (match(Tok::Slash)) {
            u.module += "/";
            if (at(Tok::DotDot)) {
                u.module += "..";
                advance();
            } else if (match(Tok::Dot)) {
                u.module += ".";
            } else {
                u.module += expect_ident("module path component");
            }
        }
        if (match(Tok::LBrace)) {
            while (!at(Tok::RBrace)) {
                u.names.push_back(expect_ident("imported name"));
                imported_names_.insert(u.names.back());
                if (!match(Tok::Comma))
                    break;
            }
            expect(Tok::RBrace, "'}' after imported names");
        }
        return u;
    }

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

    std::vector<Contract> parse_contract_body(bool decl) {
        std::vector<Contract> clauses;
        while (!at(Tok::RBrace)) {
            if (at(Tok::End))
                throw Error(cur().pos, "unterminated contract");
            Pos p = cur().pos;
            Contract c;
            c.pos = p;
            if (match_ident("pre")) {
                c.kind = Contract::Kind::Pre;
            } else if (match_ident("post")) {
                c.kind = Contract::Kind::Post;
                if (cur().kind == Tok::Ident && at(1).kind == Tok::Arrow) {
                    c.result_name = cur().text;
                    advance();
                    advance();
                }
            } else if (decl) {
                throw Error(cur().pos, "expected 'pre' or 'post' in contract body");
            } else {
                break;
            }

            if (match(Tok::LBrace)) {
                while (!at(Tok::RBrace)) {
                    if (at(Tok::End))
                        throw Error(cur().pos, "unterminated contract block");
                    Contract item;
                    item.kind = c.kind;
                    item.pos = c.pos;
                    item.result_name = c.result_name;
                    item.expr = parse_expr();
                    clauses.push_back(std::move(item));
                }
                expect(Tok::RBrace, "'}' after contract block");
            } else {
                c.expr = parse_expr();
                clauses.push_back(std::move(c));
            }
        }
        return clauses;
    }

    std::unique_ptr<ContractDecl> parse_contract_decl(bool pub) {
        Pos p = cur().pos;
        expect_ident("contract");
        auto c = std::make_unique<ContractDecl>();
        c->pos = p;
        c->pub = pub;
        c->name = expect_ident("contract name");
        c->params = parse_params();
        while (match(Tok::Colon)) {
            do {
                Contract base;
                base.pos = cur().pos;
                base.name = expect_ident("contract name");
                base.args = parse_args();
                c->bases.push_back(std::move(base));
            } while (match(Tok::Comma));
        }
        expect(Tok::LBrace, "'{' in contract declaration");
        c->clauses = parse_contract_body(true);
        expect(Tok::RBrace, "'}' after contract declaration");
        return c;
    }

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

    static bool continues_expression(Tok k) {
        switch (k) {
        case Tok::Plus:
        case Tok::Minus:
        case Tok::Star:
        case Tok::Slash:
        case Tok::Percent:
        case Tok::EqEq:
        case Tok::NotEq:
        case Tok::Le:
        case Tok::Ge:
        case Tok::AndAnd:
        case Tok::OrOr:
        case Tok::Lt:
        case Tok::Gt:
        case Tok::Assign:
        case Tok::PlusEq:
        case Tok::MinusEq:
        case Tok::StarEq:
        case Tok::SlashEq:
        case Tok::PercentEq:
        case Tok::Comma:
        case Tok::Dot:
        case Tok::LParen:
        case Tok::LBracket:
            return true;
        default:
            return false;
        }
    }

    size_t find_indented_body(Pos indent) const {
        for (size_t k = i_; k + 1 < tokens_.size(); k++) {
            const Token& t = tokens_[k];
            if (t.kind == Tok::End || t.kind == Tok::LBrace || t.kind == Tok::RBrace)
                break;
            if (t.pos.line <= indent.line || t.pos.col <= indent.col)
                continue;
            const Token& prev = tokens_[k - 1];
            if (prev.pos.line < t.pos.line && !continues_expression(prev.kind))
                return k;
        }
        return kNoLimit;
    }

    size_t find_block_start() const {
        int depth = 0;
        for (size_t k = i_; k + 1 < tokens_.size(); k++) {
            const Token& t = tokens_[k];
            if (t.kind == Tok::End)
                break;
            if (t.kind == Tok::LParen || t.kind == Tok::LBracket)
                depth++;
            else if (t.kind == Tok::RParen || t.kind == Tok::RBracket)
                depth--;
            else if (t.kind == Tok::LBrace && depth == 0)
                return k;
            else if (t.kind == Tok::RBrace && depth == 0)
                break;
        }
        return kNoLimit;
    }

    BlockPtr parse_control_body(Pos indent) {
        if (at(Tok::LBrace))
            return parse_block();
        if (cur().pos.line > indent.line && cur().pos.col > indent.col) {
            auto b = std::make_unique<Block>();
            b->pos = cur().pos;
            b->stmts.push_back(parse_stmt());
            return b;
        }
        throw Error(cur().pos, "expected '{' or an indented body");
    }

    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();
            else if (!at(Tok::Assign))
                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;
            size_t boundary = find_indented_body(p);
            size_t saved_limit = limit_;
            if (boundary != kNoLimit)
                limit_ = boundary;
            if (cur().kind == Tok::Ident && at(1).kind == Tok::Ident && at(1).text == "in") {
                s->name = cur().text;
                advance();
                advance();
                ExprPtr first = parse_expr();
                if (match(Tok::DotDot)) {
                    s->kind = Stmt::Kind::ForRange;
                    s->lo = std::move(first);
                    s->hi = parse_expr();
                } else {
                    s->kind = Stmt::Kind::ForIn;
                    s->expr = std::move(first);
                }
            } else {
                s->kind = Stmt::Kind::ForCond;
                s->cond = parse_expr();
            }
            limit_ = saved_limit;
            while (match(Tok::Colon)) {
                if (!match_ident("invariant"))
                    throw Error(cur().pos, "expected 'invariant' after ':'");
                size_t block = find_block_start();
                size_t invariant_limit = limit_;
                if (block != kNoLimit)
                    limit_ = block;
                s->invariants.push_back(parse_expr());
                limit_ = invariant_limit;
            }
            s->block = parse_control_body(p);
            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");

        std::vector<std::string> type_params;
        if (match(Tok::LBracket)) {
            while (!at(Tok::RBracket)) {
                if (at(Tok::End))
                    throw Error(cur().pos, "unterminated generic parameter list");
                type_params.push_back(expect_ident("type parameter name"));
                while (!at(Tok::Comma) && !at(Tok::RBracket) && !at(Tok::End))
                    advance();
                match(Tok::Comma);
            }
            expect(Tok::RBracket, "']' after type parameters");
        }
        fn->type_params = type_params;
        auto saved_type_params = type_params_;
        type_params_.clear();
        for (auto& name : type_params)
            type_params_.insert(name);

        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 && at(1).kind == Tok::Arrow) {
                    c.result_name = cur().text;
                    advance();
                    advance();
                }
                c.expr = parse_expr();
                fn->contracts.push_back(std::move(c));
            } else if (cur().kind == Tok::Ident) {
                Contract c;
                c.pos = p;
                c.name = expect_ident("contract name");
                c.args = parse_args();
                fn->contracts.push_back(std::move(c));
            } else {
                throw Error(cur().pos, "expected a contract name after ':'");
            }
        }

        if (match(Tok::Arrow)) {
            fn->arrow = parse_expr();
        } else {
            fn->body = parse_block();
        }
        type_params_ = std::move(saved_type_params);
        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;
        Pos indent = p;
        if (i_ > 0) {
            const Token& prev = tokens_[i_ - 1];
            if (prev.kind == Tok::Ident && prev.text == "else" && prev.pos.line == p.line)
                indent = prev.pos;
        }
        expect_ident("if");
        auto e = std::make_unique<Expr>();
        e->kind = Expr::Kind::If;
        e->pos = p;
        size_t boundary = find_indented_body(indent);
        size_t saved_limit = limit_;
        if (boundary != kNoLimit)
            limit_ = boundary;
        e->cond = parse_expr();
        limit_ = saved_limit;
        e->then_e = make_block_expr(parse_control_body(indent), p);
        if (match_ident("else")) {
            if (is_ident("if")) {
                e->else_e = parse_if_expr();
            } else {
                e->else_e = make_block_expr(parse_control_body(indent), p);
            }
        }
        return e;
    }

    Pattern parse_pattern() {
        Pattern pat;
        pat.pos = cur().pos;
        if (is_ident("_")) {
            pat.wildcard = true;
            advance();
            return pat;
        }
        pat.ctor = expect_ident("pattern constructor");
        while (match(Tok::Dot))
            pat.ctor += "." + expect_ident("variant name after '.'");
        if (match(Tok::LParen)) {
            while (!at(Tok::RParen)) {
                pat.binders.push_back(expect_ident("pattern binding"));
                if (!match(Tok::Comma))
                    break;
            }
            expect(Tok::RParen, "')' after pattern bindings");
        }
        return pat;
    }

    ExprPtr parse_match_expr() {
        Pos p = cur().pos;
        expect_ident("match");
        auto e = std::make_unique<Expr>();
        e->kind = Expr::Kind::Match;
        e->pos = p;
        e->lhs = parse_expr();
        expect(Tok::LBrace, "'{' after match value");
        while (!at(Tok::RBrace)) {
            if (at(Tok::End))
                throw Error(cur().pos, "unterminated match");
            MatchArm arm;
            arm.pat = parse_pattern();
            expect(Tok::Arrow, "'=>' in match arm");
            arm.body = parse_expr();
            e->arms.push_back(std::move(arm));
        }
        expect(Tok::RBrace, "'}' after match arms");
        return e;
    }

    ExprPtr parse_record_lit() {
        Pos p = cur().pos;
        auto e = std::make_unique<Expr>();
        e->kind = Expr::Kind::RecordLit;
        e->pos = p;
        e->text = expect_ident("type name");
        if (match(Tok::LBracket)) {
            std::vector<TypePtr> args;
            while (!at(Tok::RBracket)) {
                args.push_back(parse_type());
                if (!match(Tok::Comma))
                    break;
            }
            expect(Tok::RBracket, "']' after type arguments");
            auto ref = t_generic_ref(e->text, std::move(args));
            auto known = named_types_.find(e->text);
            if (known != named_types_.end())
                ref->base = known->second;
            e->lit_type = std::move(ref);
        }
        expect(Tok::LBrace, "'{' in record literal");
        while (!at(Tok::RBrace)) {
            if (at(Tok::End))
                throw Error(cur().pos, "unterminated record literal");
            e->names.push_back(expect_ident("field name"));
            expect(Tok::Assign, "'=' after field name");
            e->args.push_back(parse_expr());
            match(Tok::Comma);
        }
        expect(Tok::RBrace, "'}' after record fields");
        return e;
    }

    ExprPtr parse_lambda() {
        Pos p = cur().pos;
        expect_ident("fn");
        auto e = std::make_unique<Expr>();
        e->kind = Expr::Kind::Lambda;
        e->pos = p;
        expect(Tok::LParen, "'(' after 'fn'");
        while (!at(Tok::RParen)) {
            Param param;
            param.pos = cur().pos;
            param.name = expect_ident("parameter name");
            if (!at(Tok::Comma) && !at(Tok::RParen))
                param.type = parse_type();
            e->params.push_back(std::move(param));
            if (!match(Tok::Comma))
                break;
        }
        expect(Tok::RParen, "')' after lambda parameters");
        if (!at(Tok::Arrow) && !at(Tok::LBrace))
            e->lambda_ret = parse_type();
        if (match(Tok::Arrow))
            e->arrow = parse_expr();
        else if (at(Tok::LBrace))
            e->block = parse_block();
        else
            throw Error(cur().pos, "expected '=>' or '{' after lambda parameters");
        return e;
    }

    ExprPtr parse_cast() {
        Pos p = cur().pos;
        std::string keyword = cur().text;
        advance();
        expect(Tok::LBracket, "'[' after cast keyword");
        TypePtr target = parse_type();
        expect(Tok::RBracket, "']' after cast target type");
        expect(Tok::LParen, "'(' after cast target type");
        auto e = std::make_unique<Expr>();
        e->kind = Expr::Kind::Cast;
        e->pos = p;
        e->op = keyword == "cast" ? "cast" : "trunc";
        e->ty = target;
        e->lhs = parse_expr();
        expect(Tok::RParen, "')' after cast value");
        return e;
    }

    bool record_lit_ahead() const {
        if (cur().kind != Tok::Ident)
            return false;
        if (at(1).kind == Tok::LBrace)
            return true;
        if (at(1).kind != Tok::LBracket)
            return false;
        int depth = 0;
        for (size_t k = 1;; k++) {
            Tok kind = at(k).kind;
            if (kind == Tok::End)
                return false;
            if (kind == Tok::LBracket)
                depth++;
            else if (kind == Tok::RBracket) {
                depth--;
                if (depth == 0)
                    return at(k + 1).kind == Tok::LBrace;
            }
        }
    }

    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("cast") || is_ident("trunc") || is_ident("truncate")) &&
                at(1).kind == Tok::LBracket)
                return parse_cast();
            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();
            if (is_ident("match"))
                return parse_match_expr();
            if (is_ident("fn"))
                return parse_lambda();
            if (record_lit_ahead()) {
                auto rt = named_types_.find(cur().text);
                bool uppercase = !cur().text.empty() &&
                                 std::isupper(static_cast<unsigned char>(cur().text[0]));
                if (at(1).kind == Tok::LBracket ||
                    (rt != named_types_.end() && rt->second->kind == Type::Kind::Record) ||
                    uppercase || imported_names_.count(cur().text))
                    return parse_record_lit();
            }
            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 (match(Tok::ColonColon)) {
                if (e->kind != Expr::Kind::Var)
                    throw Error(cur().pos, "qualified name must start with a module");
                e->text += "::" + expect_ident("name after '::'");
                continue;
            }
            if (at(Tok::LParen)) {
                auto call = std::make_unique<Expr>();
                call->kind = Expr::Kind::Call;
                call->pos = e->pos;
                if (e->kind == Expr::Kind::Field) {
                    auto recv = std::move(e->lhs);
                    auto callee = std::make_unique<Expr>();
                    callee->kind = Expr::Kind::Var;
                    callee->pos = e->pos;
                    callee->text = e->text;
                    call->lhs = std::move(callee);
                    call->args = parse_args();
                    call->args.insert(call->args.begin(), std::move(recv));
                } else {
                    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;
            }
            if (match(Tok::Question)) {
                auto attempt = std::make_unique<Expr>();
                attempt->kind = Expr::Kind::Try;
                attempt->pos = e->pos;
                attempt->lhs = std::move(e);
                e = std::move(attempt);
                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_is() {
        ExprPtr l = parse_comparison();
        if (match_ident("is")) {
            auto e = std::make_unique<Expr>();
            e->kind = Expr::Kind::Is;
            e->pos = l->pos;
            e->lhs = std::move(l);
            e->pattern = parse_pattern();
            return e;
        }
        return l;
    }

    ExprPtr parse_equality() {
        ExprPtr l = parse_is();
        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_is(), 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 haze