Search code examples
swifttypescompiler-constructionstandard-librarytype-systems

What is the basic type that underlies all other Swift types?


I'm currently trying to get a better understanding of Apple's open-source Swift compiler on GitHub. After using Swift for several years, I've gotten used to the philosophy of defining important types like Int and Character in the standard library as structs, like any other type (opposed to Java and C, that handle int and char as primitive types in their own way). However, if Int is a struct, I would assume it is built on some other, lower-level type that is stored as a field (variable) in the Int struct. And if this type is itself a struct, what type is it built on?

Essentially, the question boils down to the following: What is the "root" type in Swift? In other words: If we view the set of Swift types in a program as an inductively defined set (user-defined types may use Int and Character, which are themselves built on other types), what defines the "base case"? I would assume that at least one primitive type that underlies all other is handled as a special case by the compiler.


Solution

  • The primitive-looking types you see defined in the Standard Library are all wrappers of built-in types that aren't publicly exposed. These are prefixed with Builtin., and as far as I understand, aren't Swift types at all. The compiler recognizes access to these constants, and give them special treatment.

    I couldn't find any documentation that lists them all out, but I did find the swift::getBuiltinType function, which can look them all up. These types include the usual suspects like ints, floats and pointers, but also more curious cases like RawUnsafeContinuation, Job, and such.

    At the time of writing, this is the current list at the time of writing. I added some notes for the ones I know about: