I was going through the code behind some of the basic types in Rust, e.g. the pleasantly simple implementation of Option<T>
or the weird macro magic behind tuple
and I was able to find all of the types that I wanted in libcore. All except for one - bool
. I couldn't find it anywhere else either.
Where is the code behind bool
in Rust? I know this is not the most novel type out there, but I was surprised I could not find it.
Thanks to the answers by Francis and rodrigo, I noticed that the code I found for other primitives was just their traits and related macros, but not actual implementations.
The Rust book states that the primitives are built-in to the language, but I'm not satisfied with this explanation. When were they built in? Can it be traced to the time when the Rust compiler was first built with Rust or did it happen when it was still built in OCaml? Does any relevant code exist?
So here's a bit more information about what goes on in the compiler. For starters, as has already been mentioned, the actual operations that occur with booleans are entirely handled by LLVM, and get directly translated to the corresponding CPU instructions. While there are some cases where code just magically appears due to bootstrapping, this is not one of them. The compiler is specifically written to handle these types and emit the correct LLVM instructions.
For the earliest parts of compilation (e.g. during macro expansion) the type bool
isn't special. It's just some path with the identifier bool
. Eventually around here it will get converted to a primitive type. The actual definition of the type is here.
So now let's look at how the !
operator works. As I mentioned earlier, the code in libcore that does impl Not for bool
never gets used. Code in the form !expr
gets transformed into <T as Not>::not(expr)
here. However, you'll notice that it checks to see if this particular expression is in fact a method call or not, and just leaves it as !expr
if it's not meant to be a method call. How does it know? The call in MIR is just a cache lookup. The cache got populated during the type checking pass. Here is where the cache insertion occurs -- basically checking to see if the Not
trait is implemented for a given type any time it sees a !
. And you'll notice that this line specifically excludes booleans and integral types, which end up compiling down to LLVM instructions directly.
That's the rough picture of how it's defined. You'll find similar code in the same files for other primitives. In theory there could be some line somewhere that was enum bool { true, false }
-- but ultimately this same code would still need to override it and emit the appropriate LLVM intrinsics, and integers couldn't be represented this way.