Way back in 2016 I wrote a couple of (now mostly outdated) blog posts talking about how types and declarations are represented in the compiler, and at the time I promised a third installment which would discuss generics. A few of you have asked me about this over the years...
Well, I finally got around to starting a write up about how generics work last year, and I think I its finally in good enough shape that I can release the first part of what is going to be a three part series. So here it is:
- PDF: http://download.swift.org/docs/assets/generics.pdf
- Source code: swift/docs/Generics at main · apple/swift · GitHub
The target audience is Swift compiler developers: if you've previously encountered GenericSignatures, GenericEnvironments, SubstitutionMaps and ProtocolConformances and found them slightly mysterious, this is definitely for you. You might also want to take a look if you're interested in programming language design or type systems in general.
(This won't actually teach you how to write generic code though! That's what The Swift Programming Language is for, I'm not trying to compete with that.)
There was a bit of scope creep. The first half of Part I begins with a big-picture overview of the key ideas behind Swift generics, and then goes on to talk about foundational material that's important to understanding the Swift compiler in general: the compilation pipeline, module system, request evaluator, types, and declarations. The second half of Part I actually dives into the details of the generics implementation in earnest; starting with the AST for generic declarations, and then going on to talk about generic signatures, substitution maps, conformances, and generic environments.
The still unfinished Part II will explain type resolution, building generic signatures, extensions and conditional conformances, conformance paths, opaque return types and existential types. Part III will talk about how the requirement machine implements generic signature queries and requirement minimization. The work-in-progress material is in the source but it needs a lot of work and it's conditionally compiled out of the PDF I'm releasing for now.