ALL INTELLIGENCE
Hacker News AIT2·Tools

Type-C Adds Variants, Generics and Pattern Matching to C11

Original title: Show HN: Type-C – variants, options, generics and pattern matching for C
58AI Score

Type-C is a superset of C11 that adds the types C lacks: variants checked by match, distinct types for ids and units, generic types, and errors-as-values with try and defer. Its compiler typec takes the same command line as cc, lowers Type-C into readable C, and hands it to the C compiler, so existing C11 files are already Type-C files and adoption can proceed one file at a time. The project is early: every example on the page works today, but the rest of the language is designed yet unbuilt.

Full Report

Contents3 sections

Type-C

Type-C is C11 with the types C is missing: variants that match checks, distinct types for ids and units, generic types, and errors as values with try and defer. Its compiler, typec, takes the command line of cc, turns Type-C into C that you can read, and hands that C to your C compiler. A C11 file is already a Type-C file, so a program adopts it one file at a time.

Type-C is early: every example on this page works today, and the rest of the language is designed but not built yet (Status).

Installing

With Homebrew, on macOS or Linux:

BASH
brew install stass/tap/typec
typec --version
man typec

Homebrew builds typec from the release source with OCaml and dune. typec hands its C to cc unless told otherwise (Choosing the backend). To build it from a checkout instead, see Try it.

A first look

An evaluator of arithmetic expression trees, which reports a division by zero or an overflow as a value instead of crashing. Like every C and Type-C example in this README, it is checked by the tests.

C
#include <limits.h>
#include <stdio.h>

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

type eval_error = | DivByZero | Overflow;

/* With a 32-bit int, long long holds every sum, product and quotient. */
static result(int, eval_error)
fit(long long n)
{
	if (n < INT_MIN || n > INT_MAX)
		return (Err(Overflow));
	return (Ok((int)n));
}

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)));
	case Mul(l, r):
		return (fit((long long)try eval(l) * try eval(r)));
	case Div(l, r):
		d = try eval(r);
		if (d == 0)
			return (Err(DivByZero));
		return (fit((long long)try eval(l) / d));
	}
}

static void
show(const expr *e)
{
	match (eval(e)) {
	case Ok(value):
		printf("%d\n", value);
		break;
	case Err(DivByZero):
		printf("division by zero\n");
		break;
	case Err(Overflow):
		printf("overflow\n");
		break;
	}
}

int
main(void)
{
	expr two = Num(2), three = Num(3), four = Num(4), zero = Num(0);
	expr sum = Add(&three, &four), ratio = Div(&sum, &zero);
	expr good = Mul(&two, &sum), bad = Mul(&two, &ratio);

	show(&good);	/* 2 * (3 + 4) */
	show(&bad);	/* 2 * ((3 + 4) / 0) */
}

It builds with the options of cc and prints:

BASH
$ typec -std=c11 -Wall -Wextra -o eval eval.tc
$ ./eval
14
division by zero

What it shows:

  • Variants. expr and eval_error are closed sums: a value is exactly one of the cases, and holds the fields of that case only. Code reaches the fields by naming them in a case, so Type-C code cannot read an Add as a Num.
  • An exhaustive match. Each match here covers every case, with no default. Add a Sub case to expr, and the build stops at the match in eval until it handles Sub (Variants and match). In show, Err(DivByZero) nests one pattern in another, so one match tells the errors apart.
  • result and try. result(int, eval_error) is a variant that every Type-C file has: Ok of an int, or Err of an eval_error. try eval(l) gives the value of an Ok, or returns that Err from the function at once: the division by zero inside bad comes up through the Mul above it to show (result and try). try stands inside an expression, as in try eval(l) + try eval(r): the operands of the tries run first, left to right, and the first error returns.
  • No runtime. typec writes C: a variant becomes a structure of a tag and a union of the fields of its cases, a match a switch on the tag, and try an early return (What the C looks like). The rest is C: the headers, the pointers, printf, the arithmetic in long long, and the C compiler that builds it.

What Type-C adds to C explains each new piece, and shows the mistakes each one rules out. The tutorial grows a C program into Type-C one feature at a time, and the language reference states the rules of each construct.

Why Type-C

  • It stays C. A C11 file keeps its meaning (principle 2). 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.
  • It does not redo what C already does. No module system, build tool or package manager of its own: a program stays translation units, headers and the build it has, and Type-C interfaces are headers that #include reads.
  • No runtime. No hidden allocation, garbage collector, exceptions or runtime library, and nothing added to the link; principle 4 lists the few places where typec adds code that the source does not spell out.
  • One toolchain. typec writes C and hands it to your GCC or Clang: the same headers, the same compiler, the same options but a few, the same ABI, and the same debugger, which steps through the lines of the .tc file (with gaps in the debug information still).
  • Adopt it one file at a time. Rename one .c file to .tc, build with CC=typec and a build rule for .tc files, and use the new types where they help. The other files do not change (Adopting one file).
  • Not another language at the boundary. Rust, Zig and OCaml call C through bindings or stubs, and C code gains their checks only when it is rewritten in them; C++ compiles only some C. Type-C's checks start in the one file that you rename. Safe Rust and OCaml are memory safe, and Type-C is not (Why not just...).
  • Costs measured against hand-written C. On a real library, the Type-C rewrite parses as fast as a hand-written C twin, within the noise of the measurement, and its object code is 2.8% (Clang) to 11.9% (GCC) larger (Measured on a real library).
  • Claims only what is checked. Each guarantee says what it depends on (principle 5), and the tests check each C and Type-C example on this page, on GCC and Clang.

(注:更多技术实现细节与完整 API 文档请查阅原项目 README)


作者发帖说明(HN):

I love C, but often using it for parsing, tree walking or complex error handling leads to spaghetti code.

Of course there is Swift, Ocaml or Rust for situations like that, but then you are either forced to convert the entire codebase, or add a runtime library or go through the pain of bridging C to the new language. Sometimes there are no compilers for the target architecture too when you are working on embedded stuff.

This is where Type-C comes in. It works as a preprocessor like TypeScript and calls the original C driver behind the scenes. Your code stays normal C for the most part, so you can predict how the code will be laid out. TypeC is a full superset of C11, so any C11 code compiles as is.

Want to use TypeC just for one file? Rename to .tc and use the features you want, the rest of the codebase stays the same. This works for kernel or baremetal code too as there is no runtime or extra libararies.

There are examples of TypeC code as well as real-world tests of converting existing code to TypeC on the GitHub page.

This is how the code looks like for an expression evaluator: type expr = | Num(int value) | Add(const expr l, const exprr) | Mul(const expr l, const exprr) | Div(const expr l, const exprr);

Text
  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)));
      case Mul(l, r):
       ...