Type-C 为 C11 补齐变体类型与泛型能力
Type-C 是 C11 的超集,为 C 语言补上可 match 的变体类型、用于 id 与单位的独立类型、泛型类型,以及以值形式传递的错误处理(try/defer)。其编译器 typec 接受与 cc 相同的命令行,将 Type-C 转译为可读的 C 代码再交给 C 编译器,现有 C11 文件可直接作为 Type-C 文件逐文件迁移。项目目前处于早期阶段,页面示例均可运行,但语言其余部分仍在设计之中。
报道正文
本文目录3 个章节
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:
brew install stass/tap/typec
typec --version
man typecHomebrew 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.
#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:
$ typec -std=c11 -Wall -Wextra -o eval eval.tc
$ ./eval
14
division by zeroWhat it shows:
- Variants.
exprandeval_errorare 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 acase, so Type-C code cannot read anAddas aNum. - An exhaustive
match. Eachmatchhere covers every case, with nodefault. Add aSubcase toexpr, and the build stops at thematchinevaluntil it handlesSub(Variants andmatch). Inshow,Err(DivByZero)nests one pattern in another, so onematchtells the errors apart. resultandtry.result(int, eval_error)is a variant that every Type-C file has:Okof anint, orErrof aneval_error.try eval(l)gives the value of anOk, or returns thatErrfrom the function at once: the division by zero insidebadcomes up through theMulabove it toshow(resultandtry).trystands inside an expression, as intry eval(l) + try eval(r): the operands of the tries run first, left to right, and the first error returns.- No runtime.
typecwrites C: a variant becomes a structure of a tag and a union of the fields of its cases, amatchaswitchon the tag, andtryan early return (What the C looks like). The rest is C: the headers, the pointers,printf, the arithmetic inlong 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
#includereads. - No runtime. No hidden allocation, garbage collector, exceptions
or runtime library, and nothing added to the link;
principle 4 lists the few places where
typecadds code that the source does not spell out. - One toolchain.
typecwrites 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.tcfile (with gaps in the debug information still). - Adopt it one file at a time. Rename one
.cfile to.tc, build withCC=typecand a build rule for.tcfiles, 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);
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):
...