# Type-C – variants, options, generics and pattern matching f…

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…

- **Page:** https://magpie.gallery/i/type-c-variants-options-generics-and-pattern-match-8rdw
- **Type:** Link to an idea elsewhere
- **Category:** AI & dev
- **Tags:** c, pattern-matching, preprocessor, variants, embedded

## Source

Web · stass: Type-C – variants, options, generics and pattern matching for C

- **Original:** https://news.ycombinator.com/item?id=50602561

> 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 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))); 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)); } } % typec -std=c11 -Wall -Wextra eval.tc $ ./a.out 14 division by zero Would love to hear your thoughts and feedback! https://github.com/stass/type-c

## GitHub projects

- https://github.com/stass/type-c

## Rules for reuse

- Build your own version: don't copy another product's code, look, icons, colours or copy.
- The original belongs to its author; Magpie only links to it.
- The original content's copyright belongs to its creator. Magpie doesn't download or re-upload it; we only show the link and the official preview.
