Type-C - C11 with variants, options, generics and exhaustive matching

Show HN: Type-C – variants, options, generics and pattern matching for C

Type-C extends C11 with the types C has always lacked: closed variants, distinct types, generics, and errors as values with try and defer. Its compiler, typec, takes the same command line as cc and translates Type-C into readable C that your existing compiler builds. A C11 file is already a Type-C file, so you can adopt it one file at a time without changing your toolchain, headers, or debugger. The result is safer code with no runtime overhead, catching mistakes like wrong union members and forgotten switch cases at compile time.

Type-C keeps C's declarations, statements, pointers, preprocessor and headers, and adds only what C has no way to say: closed sums, distinct types, type parameters, errors as values and cleanups.
  1. adsharma

    Why not use vlang?

    I wanted to do the same thing to python. So wrote a parser for a variant of python.

    It's spy-ast on pypi

  2. onlyrealcuzzo

    > Of course there is Swift, Ocaml or Rust

    Presumably C++ is the first thing you should mention.

  3. stass

    Realized that the post is a bit light on numbers, so here're some.

    I rewrote the parser of tomlc99 (2k lines) in Type-C as a test. I used result/try/defer for the error paths and left everything else unchanged, linking against the same C programs and tests.

    Doing fault injection with one failed allocation per run over ~1500 runs: the original C went wrong in 34 (25 leaks, 9 use-after-free); the rewrite went wrong never, sanitizers clean.

    With original toml-spec-tests files: the original leaked in 1002 of them and crashed in 9; the rewrite did neither.

    This is an example of how the code looks like for an expression evaluator:

    type expr =

    | Num(int value)

    | Add(const expr l, const expr r)

    | Mul(const expr l, const expr r)

    | Div(const expr l, const expr r);

    static result(int, eval_error)

    eval(const expr *e)

    {

    int d;

    match (*e) {

    case Num(value):

    return (Ok(value));

    case Add(l, r):

    return (fit((long long)try eval(l) + try eval(r)));

    …

    Happy to answer any questions!

More from this day

2026-11-23