Carbon’s most exciting feature is its calling convention

Last week, Chandler Carruth announced Carbon, a potential C++ replacement they’ve been working on for the past two years. It has the usual cool features you expect from a modern language: useful generics, compile-time interfaces/traits/concepts, modules, etc. – but the thing I’m most excited about is a tiny detail about the way parameters are passed there.

It’s something I’ve been thinking about in the past myself, and to my knowledge it hasn’t been done in any low-level language before, but the concept has a lot of potential. Let me explain what I’m talking about.

» read more »
Jonathan

Tutorial: Preparing libraries for CMake FetchContent

If you’re working on an executable project in C++, as opposed to a C++ library, using a package manager to get your dependencies might be overkill: If all you need is to get the source code of a library, include in your CMake project, and have it compiled from source with the rest of your project, CMake’s FetchContent module can do it for you.

If you’re a library writer, there are ways you can structure your CMake project to improve the experience for end users that use FetchContent: hide developer targets like tests, provide a zip archive that contains only the source files relevant downstream, and use GitHub actions to create it automatically.

Let’s see how.

» read more »
Jonathan

Technique: Recursive variants and boxes

There are many data structures that can be elegantly expressed using sum types. In C++ a (somewhat clunky) implementation of sum types is std::variant. However, it can’t handle recursive data structures, where one alternative contains the entire sum type again.

Let’s see how we can fix that.

» read more »
Jonathan

saturating_add vs. saturating_int – new function vs. new type?

Suppose you want to do integer arithmetic that saturates instead of overflowing. The built-in operator+ doesn’t behave that way, so you need to roll something yourself. Do you write a saturating_add() function or a new saturating_int type with overloaded operator+? What about atomic_load(x) vs. atomic<int> x? Or volatile_store(ptr, value) vs. volatile int*?

When should you provide functions that implement new behavior and when should you write a wrapper type? Let’s look at the pro and cons.

» read more »
Jonathan

Technique: Compile Time Code Generation and Optimization

C++ constexpr is really powerful. In this blog post, we’ll write a compiler that can parse a Brainfuck program given as string literal, and generate optimized assembly instructions that can then be executed at runtime. The best part: we neither have to actually generate assembly nor optimize anything ourselves! Instead we trick the compiler into doing all the hard work for us.

The same technique can be used whenever you want to specify some sort of “program” in a different way and translate it at runtime: regexes, routing tables, etc.

» read more »
Jonathan