navid/haze / commit

ea08ceb46539

Navid M <navidmomtahen@gmail.com> · 2026-12-02

parents: 90400c3cb2eb

Browse files at this commit · Download source

all: generic user defined type declarations
--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -180,6 +180,8 @@     "${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2.6/*.hz") file(GLOB baseline_27_samples CONFIGURE_DEPENDS     "${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2.7/*.hz")+file(GLOB baseline_28_samples CONFIGURE_DEPENDS+    "${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2.8/*.hz") list(SORT baseline_samples) list(SORT baseline_21_samples) list(SORT baseline_22_samples)@@ -188,10 +190,11 @@ list(SORT baseline_25_samples) list(SORT baseline_26_samples) list(SORT baseline_27_samples)+list(SORT baseline_28_samples)  foreach(source IN LISTS baseline_samples baseline_21_samples baseline_22_samples         baseline_23_samples baseline_24_samples baseline_25_samples baseline_26_samples-        baseline_27_samples)+        baseline_27_samples baseline_28_samples)     add_haze_sample_test("${source}") endforeach() add_haze_sample_test("${CMAKE_CURRENT_SOURCE_DIR}/samples/baseline_2/main.hz")--- /dev/null+++ b/TODO.md@@ -0,0 +1,6 @@+- [x] General user-defined generic type declarations (type Map[K, V] ...)+- [ ] u8/u16/u32/u64, bitwise operators, f64, bytes, UTF-8 string operations+- [ ] @cfg conditional compilation+- [ ] extern (C) functions and C-layout extern type+- [ ] String interpolation and format specs+- [ ] hazelib standard library modules and native OS bindings--- /dev/null+++ b/samples/baseline_2.8/generic_arg_count_error.hz@@ -0,0 +1,12 @@+// Wrong number of generic type arguments.++type Pair[A, B] {+    first A+    second B+}++fn use_pair(p Pair[i32]) i32 => p.first++fn main() {+    print(1)+}--- /dev/null+++ b/samples/baseline_2.8/generic_bare_param_error.hz@@ -0,0 +1,12 @@+// A bare generic type cannot be used as a parameter type.++type Pair[A, B] {+    first A+    second B+}++fn use_pair(p Pair) i32 => 1++fn main() {+    print(1)+}--- /dev/null+++ b/samples/baseline_2.8/generic_bare_type_error.hz@@ -0,0 +1,11 @@+// A generic type must be instantiated.++type Pair[A, B] {+    first A+    second B+}++fn main() {+    var p Pair = Pair{ first = 1, second = 2 }+    print(p.first)+}--- /dev/null+++ b/samples/baseline_2.8/generic_duplicate_param_error.hz@@ -0,0 +1,9 @@+// Duplicate generic parameter names are rejected.++type Pair[A, A] {+    first A+}++fn main() {+    print(1)+}--- /dev/null+++ b/samples/baseline_2.8/generic_enum_error.hz@@ -0,0 +1,10 @@+// Generic enum parameters are not supported; payload-free enums need no type.++type Choice[T] enum {+    One+    Two+}++fn main() {+    print(1)+}--- /dev/null+++ b/samples/baseline_2.8/generic_literal_args_error.hz@@ -0,0 +1,11 @@+// Generic record literals need their type arguments.++type Pair[A, B] {+    first A+    second B+}++fn main() {+    const p = Pair[i32]{ first = 1, second = 2 }+    print(p.first)+}--- /dev/null+++ b/samples/baseline_2.8/generic_modules.hz@@ -0,0 +1,12 @@+// Cross-module generic type instantiation.++use lib/pair_mod {Pair, make_pair}++fn main() {+    const p = make_pair(3, 4)+    print(p.first + p.second)++    const q = Pair[str, i32]{ first = "value", second = 9 }+    print(q.first)+    print(q.second)+}--- /dev/null+++ b/samples/baseline_2.8/generic_records.hz@@ -0,0 +1,33 @@+// Generic record declarations, nesting, inference, and mutation.++type Pair[A, B] {+    first A+    second B+}++type Box[T] {+    value T+}++fn first[A, B](p Pair[A, B]) A => p.first++fn main() {+    const p = Pair[i32, str]{ first = 1, second = "one" }+    print(first(p))+    print(p.second)++    const inner = Pair[i32, str]{ first = 2, second = "two" }+    const outer = Pair[Pair[i32, str], bool]{ first = inner, second = true }+    print(outer.first.first)+    print(outer.first.second)+    print(outer.second)++    var box = Box[i32]{ value = 5 }+    box.value = 9+    print(box.value)++    var boxes = [Box[i32]{ value = 10 }, Box[i32]{ value = 20 }]+    boxes[1].value = 30+    print(boxes[0].value)+    print(boxes[1].value)+}--- /dev/null+++ b/samples/baseline_2.8/generic_sums.hz@@ -0,0 +1,40 @@+// Generic sum types, constructor inference, and recursive instances.++type Maybe[T] = | Nothing | Just(value T)++type Tree[T] =+    | Leaf+    | Node(left Tree[T], value T, right Tree[T])++fn show_i(value Maybe[i32]) i32 => match value {+    Nothing => -1+    Just(v) => v+}++fn show_s(value Maybe[str]) str => match value {+    Nothing => "none"+    Just(v) => v+}++fn sum(tree Tree[i32]) i32 => match tree {+    Leaf => 0+    Node(left, value, right) => sum(left) + value + sum(right)+}++fn main() {+    const a = Just(7)+    print(show_i(a))++    const b Maybe[str] = Just("hello")+    print(show_s(b))++    const c Maybe[i32] = Nothing+    print(show_i(c))++    if a is Just(v) {+        print(v)+    }++    const tree = Node(Leaf, 2, Node(Leaf, 3, Leaf))+    print(sum(tree))+}--- /dev/null+++ b/samples/baseline_2.8/generic_unknown_arg_error.hz@@ -0,0 +1,12 @@+// Generic type arguments must name real types.++type Pair[A, B] {+    first A+    second B+}++fn use_pair(p Pair[i32, Missing]) i32 => p.first++fn main() {+    print(1)+}--- /dev/null+++ b/samples/baseline_2.8/lib/pair_mod.hz@@ -0,0 +1,8 @@+// Generic types shared across modules.++pub type Pair[A, B] {+    first A+    second B+}++pub fn make_pair(a i32, b i32) Pair[i32, i32] => Pair[i32, i32]{ first = a, second = b }--- a/src/codegen.cpp+++ b/src/codegen.cpp@@ -447,6 +447,8 @@             }             return Value{to, v.s, true};         }+        if (assignable(to, v.ty))+            return Value{to, v.s, true};         return v;     } @@ -870,6 +872,8 @@             return Value{e.ty, "$" + sym, true};         }         case Expr::Kind::Var: {+            if (e.ctor_type)+                return gen_construct_expr(e, {});             if (e.text == "None" && !ctors_.count("None")) {                 Value obj = alloc_object(16);                 store_at(obj, kObjectHeader, Value{t_i32(), "0", true}, t_i32());@@ -954,12 +958,9 @@             return 0;         }         if (s->kind == Type::Kind::Sum) {-            auto c = ctors_.find(p.ctor);-            if (c != ctors_.end()) {-                for (size_t i = 0; i < s->variants.size(); i++)-                    if (&s->variants[i] == c->second.variant)-                        return i;-            }+            for (size_t i = 0; i < s->variants.size(); i++)+                if (s->variants[i].name == p.ctor)+                    return i;         }         return 0;     }@@ -1106,6 +1107,17 @@         if (want)             return load_slot(slot, rt);         return Value{};+    }++    Value gen_construct_expr(Expr& e, std::vector<Value> args) {+        TypePtr sum = e.ctor_type;+        const Variant& v = *e.ctor_variant;+        FieldLayout lay = layout_fields(v.fields, 8);+        Value obj = alloc_object(sum_payload_size(sum));+        store_at(obj, kObjectHeader, Value{t_i32(), std::to_string(e.ctor_index), true}, t_i32());+        for (size_t i = 0; i < args.size(); i++)+            store_at(obj, kObjectHeader + lay.offsets[i], args[i], v.fields[i].type);+        return Value{sum, obj.s, true};     }      Value gen_construct(const std::string& name, std::vector<Value> args) {@@ -1127,10 +1139,13 @@     }      Value gen_record_lit(Expr& e) {-        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;+        TypePtr rt = e.ty;+        if (!rt || rt->kind != Type::Kind::Record) {+            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 + "'");+            rt = it->second;+        }         std::vector<Value> args;         for (auto& a : e.args)             args.push_back(gen_expr(*a));@@ -1232,10 +1247,9 @@         for (size_t i = 0; i < e.arms.size(); i++) {             if (e.arms[i].pat.wildcard)                 continue;-            auto c = ctors_.find(e.arms[i].pat.ctor);             size_t index = 0;-            for (size_t k = 0; k < c->second.sum->variants.size(); k++)-                if (&c->second.sum->variants[k] == c->second.variant)+            for (size_t k = 0; k < e.lhs->ty->variants.size(); k++)+                if (e.lhs->ty->variants[k].name == e.arms[i].pat.ctor)                     index = k;             std::string cmp = new_temp();             emit(cmp + " =w ceqw " + tag.s + ", " + std::to_string(index));@@ -1250,14 +1264,17 @@             start_block(labels[i]);             push_scope();             if (!e.arms[i].pat.wildcard) {-                auto c = ctors_.find(e.arms[i].pat.ctor);-                const Variant& v = *c->second.variant;-                FieldLayout lay = layout_fields(v.fields, 8);+                const Variant* v = nullptr;+                for (auto& candidate : e.lhs->ty->variants)+                    if (candidate.name == e.arms[i].pat.ctor)+                        v = &candidate;+                FieldLayout lay = layout_fields(v->fields, 8);                 for (size_t j = 0; j < e.arms[i].pat.binders.size(); j++) {                     if (e.arms[i].pat.binders[j] == "_")                         continue;-                    Value fv = load_at(scrutinee, kObjectHeader + lay.offsets[j], v.fields[j].type);-                    declare_local(e.arms[i].pat.binders[j], v.fields[j].type, fv);+                    Value fv =+                        load_at(scrutinee, kObjectHeader + lay.offsets[j], v->fields[j].type);+                    declare_local(e.arms[i].pat.binders[j], v->fields[j].type, fv);                 }             }             Value bv = gen_branch_value(*e.arms[i].body);@@ -1528,9 +1545,11 @@                 TypePtr bt = e.cond->pattern.binder_types[j];                 Value payload;                 if (s->kind == Type::Kind::Sum) {-                    auto c = ctors_.find(e.cond->pattern.ctor);-                    const Variant& v = *c->second.variant;-                    FieldLayout lay = layout_fields(v.fields, 8);+                    const Variant* v = nullptr;+                    for (auto& candidate : s->variants)+                        if (candidate.name == e.cond->pattern.ctor)+                            v = &candidate;+                    FieldLayout lay = layout_fields(v->fields, 8);                     payload = load_at(subject, kObjectHeader + lay.offsets[j], bt);                 } else {                     payload = load_at(subject, kObjectHeader + 8, bt);@@ -1667,6 +1686,9 @@         std::vector<Value> args;         for (auto& a : e.args)             args.push_back(gen_expr(*a));++        if (e.ctor_type)+            return gen_construct_expr(e, std::move(args));          if (!ctors_.count(name) && (name == "Some" || name == "OK" || name == "Error"))             return gen_wrapped(e, name);--- a/src/haze.h+++ b/src/haze.h@@ -52,6 +52,7 @@         Enum,         Option,         Result,+        GenericRef,         Function,         Param,         Unknown@@ -60,6 +61,8 @@     TypePtr elem;     TypePtr err;     std::string name;+    TypePtr base;+    std::vector<std::string> type_params;     std::vector<Field> fields;     std::vector<Variant> variants;     std::vector<TypePtr> params;@@ -82,6 +85,9 @@ TypePtr t_enum(const std::string& name); TypePtr t_option(TypePtr elem); TypePtr t_result(TypePtr ok, TypePtr err);+TypePtr t_generic_ref(const std::string& name, std::vector<TypePtr> args);+TypePtr instantiate_generic_type(const TypePtr& tmpl, const std::vector<TypePtr>& args);+bool contains_type_param(const TypePtr& t); TypePtr t_function(std::vector<TypePtr> params, TypePtr ret); TypePtr t_param(const std::string& name); TypePtr t_unknown(const std::string& name);@@ -215,6 +221,10 @@     TypePtr lambda_ret;     BlockPtr block;     Pattern pattern;+    TypePtr lit_type;+    TypePtr ctor_type;+    const Variant* ctor_variant = nullptr;+    int ctor_index = -1; };  struct Stmt;--- a/src/module.cpp+++ b/src/module.cpp@@ -330,6 +330,28 @@             return t_option(resolve_type(t->elem, p));         case Type::Kind::Result:             return t_result(resolve_type(t->elem, p), resolve_type(t->err, p));+        case Type::Kind::GenericRef: {+            TypePtr base = t->base;+            if (!base)+                base = resolve_type_name(t->name, p);+            std::vector<TypePtr> args;+            for (auto& arg : t->params) {+                TypePtr resolved_arg = resolve_type(arg, p);+                if (resolved_arg && resolved_arg->kind == Type::Kind::Unknown)+                    throw Error(p, "unknown type '" + resolved_arg->name + "'");+                args.push_back(resolved_arg);+            }+            std::string base_name = base ? base->name : t->name;+            if (base && base->type_params.size() != args.size())+                throw Error(p, "generic type '" + base->name + "' expects " ++                                   std::to_string(base->type_params.size()) ++                                   " type arguments");+            if (base && !contains_type_param(t_generic_ref(base_name, args)))+                return instantiate_generic_type(base, args);+            auto ref = t_generic_ref(base_name, std::move(args));+            ref->base = base;+            return ref;+        }         case Type::Kind::Function: {             std::vector<TypePtr> params;             for (auto& param : t->params)@@ -455,6 +477,8 @@             TypePtr resolved = resolve_type_name(e.text, e.pos);             if (resolved)                 e.text = resolved->name;+            if (e.lit_type)+                e.lit_type = resolve_type(e.lit_type, e.pos);             for (auto& a : e.args)                 resolve_expr(*a);             break;--- a/src/parser.cpp+++ b/src/parser.cpp@@ -172,6 +172,20 @@                               ? 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);@@ -187,16 +201,51 @@         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))+                if (at(Tok::End)) {+                    restore();                     throw Error(cur().pos, "unterminated enum declaration");+                }                 Variant v;                 v.pos = cur().pos;                 v.name = expect_ident("enum variant");@@ -204,6 +253,7 @@                 match(Tok::Comma);             }             expect(Tok::RBrace, "'}' after enum variants");+            restore();             return t;         } @@ -210,16 +260,21 @@         bool is_sum = match(Tok::Assign);         if (!is_sum && at(Tok::Pipe))             is_sum = true;-        if (!is_sum && !at(Tok::LBrace) && !at(Tok::Pipe))+        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))+            if (!at(Tok::Pipe)) {+                restore();                 throw Error(cur().pos, "expected '|' in sum type declaration");+            }             while (match(Tok::Pipe)) {                 Variant v;                 v.pos = cur().pos;@@ -238,13 +293,16 @@                 }                 t->variants.push_back(std::move(v));             }+            restore();             return t;         }          expect(Tok::LBrace, "'{' in record declaration");         while (!at(Tok::RBrace)) {-            if (at(Tok::End))+            if (at(Tok::End)) {+                restore();                 throw Error(cur().pos, "unterminated type declaration");+            }             Field f;             f.pos = cur().pos;             f.name = expect_ident("field name");@@ -253,6 +311,7 @@             match(Tok::Comma);         }         expect(Tok::RBrace, "'}' after record fields");+        restore();         return t;     } @@ -799,6 +858,20 @@         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))@@ -857,6 +930,28 @@         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() {@@ -895,11 +990,12 @@                 return parse_match_expr();             if (is_ident("fn"))                 return parse_lambda();-            if (at(1).kind == Tok::LBrace) {+            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 ((rt != named_types_.end() && rt->second->kind == Type::Kind::Record) ||+                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();             }--- a/src/sema.cpp+++ b/src/sema.cpp@@ -97,6 +97,10 @@         e->arms.push_back(std::move(copy));     }     e->pattern = src.pattern;+    e->lit_type = src.lit_type;+    e->ctor_type = src.ctor_type;+    e->ctor_variant = src.ctor_variant;+    e->ctor_index = src.ctor_index;     if (src.block)         e->block = clone_block(*src.block, subst);     return e;@@ -118,6 +122,16 @@         return t_option(substitute_type(t->elem, subst));     case Type::Kind::Result:         return t_result(substitute_type(t->elem, subst), substitute_type(t->err, subst));+    case Type::Kind::GenericRef: {+        std::vector<TypePtr> args;+        for (auto& arg : t->params)+            args.push_back(substitute_type(arg, subst));+        if (t->base && !contains_type_param(t_generic_ref(t->name, args)))+            return instantiate_generic_type(t->base, args);+        auto ref = t_generic_ref(t->name, std::move(args));+        ref->base = t->base;+        return ref;+    }     case Type::Kind::Function: {         std::vector<TypePtr> params;         for (auto& p : t->params)@@ -178,6 +192,17 @@     }     for (auto& bt : e.pattern.binder_types)         bt = substitute_type(bt, subst);+    e.lit_type = substitute_type(e.lit_type, subst);+    e.ctor_type = substitute_type(e.ctor_type, subst);+    if (e.ctor_type && e.ctor_variant) {+        std::string ctor_name = e.ctor_variant->name;+        for (size_t i = 0; i < e.ctor_type->variants.size(); i++)+            if (e.ctor_type->variants[i].name == ctor_name) {+                e.ctor_variant = &e.ctor_type->variants[i];+                e.ctor_index = static_cast<int>(i);+                break;+            }+    }     if (e.block)         substitute_block_types(*e.block, subst); }@@ -298,9 +323,15 @@                         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};+                    if (t->type_params.empty()) {+                        if (ctors_.count(v.name) || generic_ctors_.count(v.name))+                            throw Error(v.pos, "duplicate constructor '" + v.name + "'");+                        ctors_[v.name] = CtorInfo{t, &v};+                    } else {+                        if (ctors_.count(v.name) || generic_ctors_.count(v.name))+                            throw Error(v.pos, "duplicate constructor '" + v.name + "'");+                        generic_ctors_[v.name].push_back(GenericCtorInfo{t, &v});+                    }                 }             }         }@@ -367,6 +398,11 @@ private:     struct CtorInfo {         TypePtr sum;+        const Variant* variant;+    };++    struct GenericCtorInfo {+        TypePtr tmpl;         const Variant* variant;     }; @@ -374,6 +410,7 @@     SigMap sigs_;     std::unordered_map<std::string, TypePtr> types_;     std::unordered_map<std::string, CtorInfo> ctors_;+    std::unordered_map<std::string, std::vector<GenericCtorInfo>> generic_ctors_;     std::unordered_map<std::string, ContractDecl*> contracts_;     std::unordered_map<std::string, TypePtr> globals_;     std::unordered_map<std::string, Function*> functions_by_name_;@@ -390,6 +427,18 @@             throw Error(p, "missing type");         if (t->kind == Type::Kind::Unknown)             throw Error(p, "unknown type '" + t->name + "'");+        if (!t->type_params.empty())+            throw Error(p, "generic type '" + t->name + "' requires type arguments");+        if (t->kind == Type::Kind::GenericRef) {+            if (!t->base)+                throw Error(p, "unknown generic type '" + t->name + "'");+            for (auto& arg : t->params)+                validate_type(arg, p);+            if (t->base && t->base->type_params.size() != t->params.size())+                throw Error(p, "generic type '" + t->base->name + "' expects " ++                                   std::to_string(t->base->type_params.size()) ++                                   " type arguments");+        }         if (t->kind == Type::Kind::List)             validate_type(t->elem, p);         if (t->kind == Type::Kind::Option)@@ -561,6 +610,7 @@         loop_depth_ = 0;          for (auto& p : fn.params) {+            validate_type(p.type, p.pos);             if (p.type->kind == Type::Kind::Unknown)                 throw Error(p.pos, "unknown type '" + p.type->name + "'");             if (p.type->kind == Type::Kind::Void)@@ -567,6 +617,7 @@                 throw Error(p.pos, "parameter cannot have type void");             scope_->declare(p.name, p.type, true, p.pos);         }+        validate_type(fn.ret, fn.pos);          std::unordered_set<std::string> post_names;         for (auto& c : fn.contracts) {@@ -834,6 +885,8 @@         if (!pattern || !actual)             return;         if (pattern->kind == Type::Kind::Param) {+            if (actual->kind == Type::Kind::Unknown)+                return;             auto it = subst.find(pattern->name);             if (it == subst.end()) {                 subst[pattern->name] = actual;@@ -843,7 +896,30 @@             return;         }         if (pattern->kind == Type::Kind::List && actual->kind == Type::Kind::List) {+            infer_type(pattern->elem, actual->elem, subst, p);+            return;+        }+        if (pattern->kind == Type::Kind::Option && actual->kind == Type::Kind::Option) {+            infer_type(pattern->elem, actual->elem, subst, p);+            return;+        }+        if (pattern->kind == Type::Kind::Result && actual->kind == Type::Kind::Result) {             infer_type(pattern->elem, actual->elem, subst, p);+            infer_type(pattern->err, actual->err, subst, p);+            return;+        }+        if (pattern->kind == Type::Kind::GenericRef && pattern->base && actual->base &&+            pattern->base == actual->base &&+            pattern->params.size() == actual->params.size()) {+            for (size_t i = 0; i < pattern->params.size(); i++)+                infer_type(pattern->params[i], actual->params[i], subst, p);+            return;+        }+        if (pattern->kind == Type::Kind::GenericRef && actual->kind == Type::Kind::GenericRef &&+            pattern->base && actual->base && pattern->base == actual->base &&+            pattern->params.size() == actual->params.size()) {+            for (size_t i = 0; i < pattern->params.size(); i++)+                infer_type(pattern->params[i], actual->params[i], subst, p);             return;         }         if (pattern->kind == Type::Kind::Function && actual->kind == Type::Kind::Function) {@@ -999,7 +1075,8 @@             return ft->ret;         } -        if (!ctors_.count(name) && (name == "Some" || name == "OK" || name == "Error")) {+        if (!ctors_.count(name) && !generic_ctors_.count(name) &&+            (name == "Some" || name == "OK" || name == "Error")) {             if (e.args.size() != 1)                 throw Error(e.pos, name + " expects exactly one argument");             TypePtr at = check_expr(*e.args[0]);@@ -1025,6 +1102,47 @@                                                     type_name(v.fields[i].type));             }             return ctor->second.sum;+        }++        auto generic_ctor = generic_ctors_.find(name);+        if (generic_ctor != generic_ctors_.end()) {+            if (generic_ctor->second.size() != 1)+                throw Error(e.pos, "ambiguous generic constructor '" + name + "'");+            const GenericCtorInfo& info = generic_ctor->second[0];+            const Variant& v = *info.variant;+            if (e.args.size() != v.fields.size())+                throw Error(e.pos, "constructor '" + name + "' expects " ++                                       std::to_string(v.fields.size()) + " arguments");+            TypeSubst subst;+            std::vector<TypePtr> arg_types;+            for (size_t i = 0; i < e.args.size(); i++) {+                TypePtr at = check_expr(*e.args[i]);+                arg_types.push_back(at);+                infer_type(v.fields[i].type, at, subst, e.args[i]->pos);+            }+            for (size_t i = 0; i < e.args.size(); i++) {+                TypePtr expected = substitute_type(v.fields[i].type, subst);+                if (!contains_type_param(expected) &&+                    !value_assignable(expected, arg_types[i], *e.args[i]))+                    throw Error(e.args[i]->pos, "argument " + std::to_string(i + 1) ++                                                    " has type " + type_name(arg_types[i]) ++                                                    ", expected " + type_name(expected));+            }+            std::vector<TypePtr> targs;+            for (auto& param : info.tmpl->type_params) {+                auto found = subst.find(param);+                targs.push_back(found == subst.end() ? t_unknown("?") : found->second);+            }+            TypePtr inst = instantiate_generic_type(info.tmpl, targs);+            for (size_t i = 0; i < inst->variants.size(); i++) {+                if (inst->variants[i].name == v.name) {+                    e.ctor_type = inst;+                    e.ctor_variant = &inst->variants[i];+                    e.ctor_index = static_cast<int>(i);+                    break;+                }+            }+            return inst;         }          if (name == "print" || name == "__gc_alloc" || name == "__gc_store" ||@@ -1177,17 +1295,17 @@                 throw Error(pat.pos, "enum variants take no bindings");             return;         }-        auto c = ctors_.find(pat.ctor);-        if (c == ctors_.end())-            throw Error(pat.pos, "unknown constructor '" + pat.ctor + "'");-        if (!same_type(s, c->second.sum))+        const Variant* variant = nullptr;+        for (auto& v : s->variants)+            if (v.name == pat.ctor)+                variant = &v;+        if (!variant)             throw Error(pat.pos, "pattern '" + pat.ctor + "' does not belong to " +                                      type_name(s));-        const Variant& v = *c->second.variant;-        if (pat.binders.size() != v.fields.size())+        if (pat.binders.size() != variant->fields.size())             throw Error(pat.pos, "pattern '" + pat.ctor + "' expects " +-                                     std::to_string(v.fields.size()) + " bindings");-        for (auto& f : v.fields)+                                     std::to_string(variant->fields.size()) + " bindings");+        for (auto& f : variant->fields)             pat.binder_types.push_back(f.type);     } @@ -1207,7 +1325,7 @@             t = t_str();             break;         case Expr::Kind::Var: {-            if (e.text == "None" && !ctors_.count("None")) {+            if (e.text == "None" && !ctors_.count("None") && !generic_ctors_.count("None")) {                 t = t_option(t_unknown("?"));                 break;             }@@ -1221,6 +1339,28 @@                 if (!c->second.variant->fields.empty())                     throw Error(e.pos, "constructor '" + e.text + "' requires arguments");                 t = c->second.sum;+                break;+            }+            auto gc = generic_ctors_.find(e.text);+            if (gc != generic_ctors_.end()) {+                if (gc->second.size() != 1)+                    throw Error(e.pos, "ambiguous generic constructor '" + e.text + "'");+                const GenericCtorInfo& info = gc->second[0];+                if (!info.variant->fields.empty())+                    throw Error(e.pos, "constructor '" + e.text + "' requires arguments");+                std::vector<TypePtr> targs;+                for (size_t i = 0; i < info.tmpl->type_params.size(); i++)+                    targs.push_back(t_unknown("?"));+                TypePtr inst = instantiate_generic_type(info.tmpl, targs);+                for (size_t i = 0; i < inst->variants.size(); i++) {+                    if (inst->variants[i].name == info.variant->name) {+                        e.ctor_type = inst;+                        e.ctor_variant = &inst->variants[i];+                        e.ctor_index = static_cast<int>(i);+                        break;+                    }+                }+                t = inst;                 break;             }             auto g = globals_.find(e.text);@@ -1448,10 +1588,24 @@             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;+            TypePtr rt = e.lit_type;+            if (rt && rt->kind == Type::Kind::GenericRef) {+                if (rt->base && !contains_type_param(rt))+                    rt = instantiate_generic_type(rt->base, rt->params);+                else+                    throw Error(e.pos, "unresolved generic record type '" + type_name(rt) + "'");+            }+            if (!rt) {+                auto it = types_.find(e.text);+                if (it == types_.end())+                    throw Error(e.pos, "unknown record type '" + e.text + "'");+                rt = it->second;+            }+            if (!rt->type_params.empty())+                throw Error(e.pos, "generic type '" + rt->name + "' requires type arguments");+            if (rt->kind != Type::Kind::Record)+                throw Error(e.pos, "unknown record type '" + type_name(rt) + "'");+            e.text = rt->name;             std::unordered_set<std::string> seen;             for (size_t i = 0; i < e.args.size(); i++) {                 TypePtr at = check_expr(*e.args[i]);--- a/src/types.cpp+++ b/src/types.cpp@@ -1,4 +1,6 @@ #include "haze.h"++#include <unordered_map>  namespace haze { @@ -69,7 +71,144 @@     auto t = make(Type::Kind::Result);     t->elem = std::move(ok);     t->err = std::move(err);+    return t;+}++TypePtr t_generic_ref(const std::string& name, std::vector<TypePtr> args) {+    auto t = make(Type::Kind::GenericRef);+    t->name = name;+    t->params = std::move(args);     return t;+}++bool contains_type_param(const TypePtr& t) {+    if (!t)+        return false;+    switch (t->kind) {+    case Type::Kind::Param:+        return true;+    case Type::Kind::List:+    case Type::Kind::Option:+        return contains_type_param(t->elem);+    case Type::Kind::Result:+        return contains_type_param(t->elem) || contains_type_param(t->err);+    case Type::Kind::GenericRef:+        for (auto& arg : t->params)+            if (contains_type_param(arg))+                return true;+        return false;+    case Type::Kind::Function:+        for (auto& param : t->params)+            if (contains_type_param(param))+                return true;+        return contains_type_param(t->ret);+    default:+        return false;+    }+}++namespace {++using GenericSubst = std::unordered_map<std::string, TypePtr>;++TypePtr substitute_generic_type(const TypePtr& t, const GenericSubst& subst,+                                std::unordered_map<std::string, TypePtr>& cache);++TypePtr instantiate_generic_impl(const TypePtr& tmpl, const std::vector<TypePtr>& args,+                                 std::unordered_map<std::string, TypePtr>& cache) {+    if (!tmpl || args.size() != tmpl->type_params.size())+        return tmpl;++    std::string key = tmpl->name + "<";+    for (size_t i = 0; i < args.size(); i++) {+        if (i)+            key += ",";+        key += type_name(args[i]);+    }+    key += ">";++    auto existing = cache.find(key);+    if (existing != cache.end())+        return existing->second;++    auto inst = make(tmpl->kind);+    inst->name = key;+    inst->base = tmpl;+    inst->params = args;+    inst->pub = tmpl->pub;+    inst->module = tmpl->module;+    cache[key] = inst;++    GenericSubst local;+    for (size_t i = 0; i < tmpl->type_params.size(); i++)+        local[tmpl->type_params[i]] = args[i];++    for (auto& f : tmpl->fields) {+        Field copy;+        copy.name = f.name;+        copy.pos = f.pos;+        copy.type = substitute_generic_type(f.type, local, cache);+        inst->fields.push_back(std::move(copy));+    }+    for (auto& v : tmpl->variants) {+        Variant copy;+        copy.name = v.name;+        copy.pos = v.pos;+        for (auto& f : v.fields) {+            Field field;+            field.name = f.name;+            field.pos = f.pos;+            field.type = substitute_generic_type(f.type, local, cache);+            copy.fields.push_back(std::move(field));+        }+        inst->variants.push_back(std::move(copy));+    }+    return inst;+}++TypePtr substitute_generic_type(const TypePtr& t, const GenericSubst& subst,+                                std::unordered_map<std::string, TypePtr>& cache) {+    if (!t)+        return t;+    switch (t->kind) {+    case Type::Kind::Param: {+        auto it = subst.find(t->name);+        return it == subst.end() ? t : it->second;+    }+    case Type::Kind::List:+        return t_list(substitute_generic_type(t->elem, subst, cache));+    case Type::Kind::Option:+        return t_option(substitute_generic_type(t->elem, subst, cache));+    case Type::Kind::Result:+        return t_result(substitute_generic_type(t->elem, subst, cache),+                        substitute_generic_type(t->err, subst, cache));+    case Type::Kind::Function: {+        std::vector<TypePtr> params;+        for (auto& p : t->params)+            params.push_back(substitute_generic_type(p, subst, cache));+        return t_function(std::move(params),+                          substitute_generic_type(t->ret, subst, cache));+    }+    case Type::Kind::GenericRef: {+        std::vector<TypePtr> args;+        for (auto& arg : t->params)+            args.push_back(substitute_generic_type(arg, subst, cache));+        if (t->base && !contains_type_param(t_generic_ref(t->name, args)))+            return instantiate_generic_impl(t->base, args, cache);+        auto ref = t_generic_ref(t->name, std::move(args));+        ref->base = t->base;+        return ref;+    }+    default:+        return t;+    }+}++} // namespace++TypePtr instantiate_generic_type(const TypePtr& tmpl, const std::vector<TypePtr>& args) {+    std::unordered_map<std::string, TypePtr> cache;+    return instantiate_generic_impl(tmpl, args, cache); }  TypePtr t_function(std::vector<TypePtr> params, TypePtr ret) {@@ -102,6 +241,14 @@         return same_type(a->elem, b->elem);     if (a->kind == Type::Kind::Result)         return same_type(a->elem, b->elem) && same_type(a->err, b->err);+    if (a->kind == Type::Kind::GenericRef) {+        if (a->name != b->name || a->params.size() != b->params.size())+            return false;+        for (size_t i = 0; i < a->params.size(); i++)+            if (!same_type(a->params[i], b->params[i]))+                return false;+        return true;+    }     if (a->kind == Type::Kind::Function) {         if (!same_type(a->ret, b->ret) || a->params.size() != b->params.size())             return false;@@ -191,6 +338,16 @@         return "Option[" + type_name(t->elem) + "]";     case Type::Kind::Result:         return "Result[" + type_name(t->elem) + ", " + type_name(t->err) + "]";+    case Type::Kind::GenericRef: {+        std::string s = t->name + "[";+        for (size_t i = 0; i < t->params.size(); i++) {+            if (i)+                s += ", ";+            s += type_name(t->params[i]);+        }+        s += "]";+        return s;+    }     case Type::Kind::Function: {         std::string s = "fn(";         for (size_t i = 0; i < t->params.size(); i++) {@@ -248,6 +405,18 @@                 to->elem->kind == Type::Kind::Unknown) &&                (same_type(to->err, from->err) || from->err->kind == Type::Kind::Unknown ||                 to->err->kind == Type::Kind::Unknown);+    if ((to->kind == Type::Kind::Record || to->kind == Type::Kind::Sum ||+         to->kind == Type::Kind::Enum) &&+        to->kind == from->kind && to->base && from->base && to->base == from->base &&+        to->params.size() == from->params.size()) {+        for (size_t i = 0; i < to->params.size(); i++) {+            if (!assignable(to->params[i], from->params[i]) &&+                to->params[i]->kind != Type::Kind::Unknown &&+                from->params[i]->kind != Type::Kind::Unknown)+                return false;+        }+        return true;+    }     if (to->kind == Type::Kind::Unknown || from->kind == Type::Kind::Unknown)         return true;     return false;