DocsLanguage Guide
Casting, Metatypes and Reflection
Casts and type tests, key paths, types as values, opening existentials, and reflection.
Most of what Sable knows about types, it knows while it compiles. Generic code is specialised for each type it is used with, some P names one concrete type, and a call is resolved before the program runs. But some questions can only be answered as the program runs: is this Animal actually a Dog? Which type does this any Shape hold? Which plugins does this program contain?
This chapter covers the tools for those questions: casts and type tests, key paths (a way to name a part of a value as a value), metatypes (types as values), opening a type or an existential so that generic code can run on it, and reflection, which describes a type's fields and members and can call them by name.
Everything here is opt-in and costs nothing until you use it. A type that is never asked about has no extra metadata, and a program that never reflects carries no reflection.
Casts and Type Tests#
Sable has five ways to change or test the type of a value. They sit at the tightest precedence level, alongside member access and calls:
| Form | Meaning |
|---|---|
x as T |
A conversion that always succeeds or is checked: numbers, upcasts, enum cases |
x unchecked as T |
A numeric conversion that never traps: wraps or truncates |
x as? T |
A dynamic downcast that gives a T? |
x as! T |
A dynamic downcast that traps when it fails |
x is T |
A test that gives a Bool, and narrows x where it is true |
Converting Numbers with as#
Sable never converts between numeric types silently. An Int is not an I64, and returning one where the other is wanted is a type error. You convert with as:
let count = 300let small = count as I16 // 300let ratio = count as F64 // 300.0let byte = count as U8 // traps: 300 does not fit in a U8as between integer types is checked: if the value doesn't fit in the target type, the program traps, just as + traps on overflow. (A package's profile can turn overflow checks off, and then as wraps instead; see Getting Started.)
When you want the bits rather than the value, write unchecked as. It never traps:
let wide: I32 = 1_000let low = wide unchecked as U8 // 232: the low 8 bits are keptlet negative = -1 unchecked as U16 // 65535let truncated = 3.99 unchecked as Int // 3: toward zerolet huge = 1e300 unchecked as I32 // 2147483647: stops at the boundlet nan = F64.nan unchecked as Int // 0An integer keeps its low bits. A float goes toward zero and stops at the target's bounds, and NaN gives 0.
Char converts to and from integers too: c as U32 is its scalar value, n as Char the character with that value, and c unchecked as U8 its low byte. There is no unchecked as Char, since there is no character to wrap to. as also converts between an enum and its underlying integer (Status.Closed as U8, 9 as Status), as Enums and Unions showed.
as? is never used between numbers. A number is always a number, so the question as? asks has no "no" answer, and the compiler refuses it.
Upcasts#
as also converts a value to a type it already is: a subclass to its superclass, or a conforming value to an existential:
let dog = Dog(name: "Rex")let animal = dog as Animallet named = dog as any NamedUsually you don't need to write these, because a Dog can go anywhere an Animal is wanted. Write them when you want to choose an overload, or to give a literal its type.
Downcasting with as? and as!#
Going the other way, from a superclass to a subclass or from an existential to a concrete type, can fail, so it's a different operator. as? gives an optional, none if the value isn't of that type:
let pets: Animal[] = [Dog(name: "Rex"), Cat(name: "Tom")]for pet in pets { if let dog = pet as? Dog { print("\(dog.name) can fetch") }}// prints "Rex can fetch"as! is the forced form: it gives the value as a T, and traps if it is not one. Use it only when a failure would be a bug:
let first = pets[0] as! Dogas? and as! work on classes (by their chain of superclasses), on existentials (any P, asking what the box holds), and on any Any. Casting an existential to a protocol asks whether the type the box holds conforms, which the runtime looks up in its conformance registry.
Testing with is#
is asks the question without converting. In the branch where it's true, the compiler narrows the variable to that type, so you don't need a second cast:
fn describe(_ animal: Animal) -> String { if animal is Dog { return "a dog called \(animal.name), who fetches \(animal.fetchCount) times a day" } return "an animal called \(animal.name)"}The same narrowing works for structural unions, as if v is Int { … } did in Enums and Unions. In a match, the patterns is T and let x as T do the same work; see Pattern Matching.
Casts That Could Never Succeed#
If the compiler can see that a cast can never succeed, it is an error rather than a cast that always fails (S3066). That covers unrelated types ("12" as Int), numbers to Bool, unchecked as on anything that isn't a number, and classes on different lines of inheritance:
class Invoice { }class Customer { }fn find(_ x: Invoice) -> Customer? { return x as? Customer // error[S3066]: 'Invoice' and 'Customer' are unrelated classes}To turn a string into a number, parse it (Int.parse(s)). A cast never parses.
Casts on Optionals#
When you test or cast an optional, is, as?, as! and the patterns is T and let x as T look at the value it holds. none is not a T, so is gives false, as? gives none, and as! traps:
let maybe: Animal? = Dog(name: "Rex")print(maybe is Dog) // truelet dog = maybe as? Dog // a Dog?, holding Rexlet nothing: Animal? = noneprint(nothing is Dog) // falseArray Literals and Existential Elements#
An array of any P holds each element in its own box. When you write an array literal where such an array is wanted, each element is converted for you:
let mixed: (any Any)[] = [1, "a", 2.5]fn show(_ values: (any Debug)[:]) { for v in values { print(v) }}show([1, "two", 3.0]) // each element boxed as an 'any Debug'If another overload takes the literal as it is (for example an Int[:]), that overload is chosen instead.
Between Growable and Fixed Arrays#
as also converts between an array that grows (T[>..] or T[>..<]) and one that is fixed at construction (T[]), in either direction. Nothing is copied: the two share their elements until one of them is changed:
var building: Int[>..] = []for i in 1...3 { building.append(i * i) }let done = building as Int[] // [1, 4, 9], sharing building's bufferKey Paths#
A key path names a route from a value to one of its parts, and the route itself is a value. You write it with a backslash:
struct Address { var city: String var zip: String?}struct Customer { var name: String var address: Address var billing: Address?}let city: KeyPath<Customer, String> = \.address.cityKeyPath<Root, Value> is a Sable.Core type. The root (what the path starts from) is the context's to say, as here, or you write it before the first dot: \Customer.address.city. The value (what it leads to) is the type of the last member.
Each step of a path is a stored or computed property, or a tuple's element. ?. reaches through an optional as it does in an expression, and then the path leads to an optional:
let billingCity = \Customer.billing?.city // KeyPath<Customer, String?>Using a Key Path#
value(of:) follows the path from a root. path is the members' names, which is useful for error messages and for code that maps fields to columns or keys:
let ada = Customer(name: "Ada", address: Address(city: "London", zip: none), billing: none)print(city.value(of: ada)) // Londonprint(city.path) // address.cityprint(billingCity.value(of: ada)) // noneprint(billingCity.path) // billing.cityappending(_:) joins two paths into one:
let letters = (\Customer.address).appending(\.city).appending(\.count)print(letters.value(of: ada)) // 6print(letters.path) // address.city.countKey Paths as Functions#
Where a function from the root to the value is wanted, a key path is one. That makes map and friends read nicely:
let customers = [ada, Customer(name: "Grace", address: Address(city: "New York", zip: none), billing: none)]print(customers.map(\.name)) // ["Ada", "Grace"]Key Paths as Arguments#
Passed as an argument, a key path waits for its parameter's type, as a closure does, so \.email works without its root. It also settles the type parameters of a generic function:
struct Table<Row> { var rows: Row[>..] fn column<V>(_ path: KeyPath<Row, V>) -> V[>..] { return rows.map(path) }}let table = Table(rows: customers)let names = table.column(\.name) // V is StringWhen two overloads differ only in whether what the path leads to is optional, one taking KeyPath<T, V> and the other KeyPath<T, V?>, the path goes to the one it fits: \.billing?.city to the second, \.name to the first.
Limits#
Key paths in Sable are read only, unlike Swift's writable key paths. There are no key paths through subscripts (\.items[0]), and none to the value itself (Swift's \.self). You can also make a key path from a closure, with a path name of your choosing: KeyPath<Int, Int>(path: "double", read: (n: Int) => n * 2).
Metatypes#
T.self#
T.self is the type T as a value. Any type can be written this way, not just a name:
let a = Int.selflet b = Int?.selflet c = Customer[].selflet d = Token[>..].selflet e = (Int, String).selflet f = (Int) -> Bool.selfA compound type is only read as a type in an expression when .self follows it. That keeps xs[0] an index and p?.x an optional chain. The one other place a type appears in an expression is a call to the empty initialiser of a dictionary or growable array type: [String: Int](), Int[>..]() and Int[>..<]().
T.Type#
The type of T.self is the metatype T.Type. Its only value is the type itself, which is known when the code is compiled (in generic code, in each specialisation), so passing one around costs nothing: at run time it is a pointer to the type's metadata, a constant. Int?.Type and Int[>..].Type are the metatypes of compound types. (A type with a nested type called Type can't use the suffix.)
A T.Type parameter is how a generic function lets its caller name T without passing a value of it, and a metatype value reaches the type's static members:
protocol Zero { static fn zero() -> Self}struct Meters: Zero { var value: F64 static fn zero() -> Meters => Meters(value: 0)}fn make<T: Zero>(_ type: T.Type) -> T { return type.zero()}let m = make(Meters.self) // T is Metersprint(m.value) // 0.0Two metatypes compare with == and !=: they are equal when they are the same type. In generic code that is decided for each specialisation.
Type, the Existential Metatype#
Type is any type at all, known only at run time, as a value. Every T.Type converts to it. You get the type of a value with type(of:), which gives its dynamic type: an object's own class (which may be a subclass of its variable's), the type an existential holds, and for any other value its static type:
let animal: Animal = Dog(name: "Rex")let t: Type = type(of: animal)print(t) // Zoo.Dog, not Zoo.AnimalA Type is Equatable (equal when it's the one type) and Hashable, so it can key a dictionary, and it prints as its name:
var labels: [Type: String] = [:]labels[t] = "dog"labels[Int.self] = "int"print(labels[type(of: animal)]!) // dogA user type's name includes its module (Zoo.Dog); a built-in's doesn't (Int?, String).
What a Type Can Tell You#
A Type describes what the runtime's metadata records about the type:
| Member | What it gives |
|---|---|
name |
The type's name, as Sable writes it: "Int?", "Zoo.Box<Int>" |
kind |
A TypeKind: .Class, .Struct, .Enum, .Union, .Optional, .Tuple, .Function, .Array, .Slice, .Existential, .Metatype, .Scalar, .String, .Reference, .Opaque, .InlineArray |
size, alignment, stride |
The value's layout in bytes |
isTrivial, isNoncopyable |
Whether it is copied as plain bits; whether it is move-only |
fieldCount, fieldName(at:), fieldOffset(at:), fieldType(at:) |
Its stored fields (a superclass's first), a tuple's elements, or an enum's or union's cases |
argumentCount, argument(at:) |
Its type arguments: a generic type's, an optional's wrapped type, an array's element, a tuple's elements |
struct Point { var x: F64 var y: F64}let p: Type = Point.selfprint("\(p.name) \(p.kind) \(p.size) bytes")for i in 0..<p.fieldCount { print(" \(p.fieldName(at: i)): \(p.fieldType(at: i)) at \(p.fieldOffset(at: i))")}Zoo.Point Struct 16 bytes x: F64 at 0 y: F64 at 8A name that the type itself has no static member of reaches the Type's member, so Int?.self.name is "Int?".
Testing Against a Type Known Only at Run Time#
A Type doesn't reach any static member of the type it holds, and doesn't convert back to a T.Type, because what it holds isn't known where the code is compiled. For the same reason a cast never targets a Type value: x is t, where t is a variable, is an error (S3098).
Instead, a Type answers two questions itself. t.isInstance(x) asks whether a value is of the type, and t.isSubtype(of: u) asks whether one type is another:
let wanted: Type = (any Named).selfprint(wanted.isInstance(animal)) // whether Dog conforms to Namedprint(Dog.self.isSubtype(of: Animal.self)) // trueprint(Int.self.isSubtype(of: (any Equatable).self)) // trueA type is a subtype of itself, of each class above it, and of an existential ((any Named & Sized).self) when it conforms to each of its protocols, which is looked up in the conformance registry. Every type is a subtype of any Any. An existential of a generic protocol instance, such as any Source<Int>, is a subtype only of itself.
Opening a Type#
A Type can't call T's static members directly, but generic code can. When you pass a Type where a generic function takes a T.Type, Sable opens it: inside the call, T is whatever type the value holds when the program runs. This is what Swift does with existential metatypes (SE-0352), and as in Swift, you write nothing at the call:
fn make<T: Zero>(_ type: T.Type) -> T { return T.zero()}fn name<T>(_ type: T.Type) -> String { return "\(T.self)"}let types: [String: Type] = ["meters": Meters.self, "seconds": Seconds.self]let made = make(types["meters"]!) // an 'any Zero', holding a Metersprint(name(type(of: animal))) // Zoo.DogThe opening only happens when no other argument says what T is, and the opening argument is evaluated before the others.
What Happens at Run Time#
The callee is compiled once for every type (in an optimised build as in a debug one) and given the value's metadata as T's. For each protocol T must conform to, the runtime asks the conformance registry for the type's witness table. If the type doesn't conform, the call traps, naming the type and the protocol, just as as! would:
fatal error: 'Zoo.Rock' does not conform to 'Zoo.Zero'If you can't be sure, test first with isSubtype(of:):
fn zeroOf(_ t: Type) { if t.isSubtype(of: (any Zero).self) { let made = make(t) print("made \(made)") } else { print("\(t) has no zero") }}any P.Type#
A type that is known to conform to a protocol P has its own metatype, any P.Type (for a protocol that isn't generic). A T.Type of a conforming T converts to it, and a Type is cast to it with as?, as! or is, which asks the registry. Opening an any P.Type can never trap:
if let zero = t as? any Zero.Type { let made = make(zero) // never a trap}An any P.Type converts to Type, and to an any Q.Type for a protocol Q that P refines. It also reaches the static members of P directly — its requirements, and what extensions of P add — opening itself the same way:
let made = zero.zero() // an 'any Zero'What the Call Gives Back#
The code after the call doesn't know T, so whatever the callee returns is erased to something it can hold:
| The callee returns | The caller gets |
|---|---|
T |
The existential of T's protocols: any Zero, any Zero & Named, or any Any with none |
T? |
An optional of that existential |
An array of T |
An array of that existential |
T.Type |
A Type |
Anything that doesn't mention T |
That, unchanged |
The Rules#
For an opening to be sound, the callee must follow some rules:
Tmay be constrained only to protocols that are not generic: not to a class, and not toProducer<Int>(S3162).- No other parameter may be of type
Tor of a type made from it, since nothing at the call can have a value of a type known only at run time. Nor may awhereclause makeTequal to another type (S3162). - A result or error that mentions
Tin any other way —(T, Int),T??,Box<T>,throws(T)— can't be erased (S3163). - A callee that is copied for each type rather than compiled once can't be opened (S3164). The diagnostic says what in its body keeps it that way.
Making Types at Run Time#
Inside an opened call, T is a type like any other. T[].self, T?.self and Box<T>.self are types built at run time from the opened one, equal to the same types written out, and T[>..] is an array you can fill with its values. That is how you build a generic type from a type known only at run time:
fn arrayOf<T>(_ type: T.Type) -> Type { return T[].self}let rows = arrayOf(t) // Zoo.Row[] when t holds Zoo.Rowprint(rows == Row[].self) // trueThe registry knows the conformances of every type the program declares. A call that opens a Type makes the witness tables, and the code to box values, for every such type that conforms to T's protocols. For a generic type made only at run time, it uses the generic declaration's conformance, compiled once for every instance. Opening a type the program has no tables for traps.
Generic Types as Values#
Write a generic type's name without its type arguments, and .self gives you the generic type itself, a GenericType. Given type arguments, it makes the type of them; given a type made from it, it gives the arguments back:
struct Pair<A, B> { let first: A let second: B}let pair = Pair.selflet made = pair.instantiate([Int.self, String.self])! // Pair<Int, String>print(made == Pair<Int, String>.self) // truelet parts = pair.arguments(of: made)! // [Int, String]instantiate gives none when there are not as many arguments as the type takes, or when one doesn't meet its constraints. arguments(of:) gives none for a type that isn't an instance of it. name and parameterCount describe the generic type.
A generic protocol's GenericType stands for its existentials. It knows their arguments, but doesn't make them:
let items = Source.self.arguments(of: (any Source<Int>).self)! // [Int]This is C#'s MakeGenericType: combine it with opening a type, and a program can build Cache<Key, Value> for types read from configuration.
Opening an Existential#
An any P is opened the same way, implicitly, in two places: when you call a requirement through it, and when you pass it to generic code.
Requirements Called Through any P#
A call through an existential runs on the value as its real type, and whatever comes back is erased again. A result of Self comes back as the existential itself; a result of one of P's associated types comes back as the existential of the protocols that associated type is constrained to (any Any if none); and an optional or array of either comes back as an optional or array of that:
protocol Shape { associatedtype Unit: Named fn doubled() -> Self fn unit() -> Unit fn measure() async -> F64}let s: any Shape = Square(side: 2)let d = s.doubled() // an 'any Shape', holding a Squarelet u = s.unit() // an 'any Named'let m = await s.measure()A get-only property of type Self, and a member of an extension of P that returns Self, work the same way. A requirement with type parameters of its own, like fn visit<T: Named>(_ item: T), is called through an existential as any other.
What Stays Out of Reach#
Some requirements can't be called through any P, because nothing sound could be done with the call:
- A parameter that mentions
Selfor an associated type, likefn same(as other: Self) -> Bool: two existentials may hold two different types, so there is no way to know the argument fits. - A result made of
Selfor an associated type in some other way, like(Self, Int)orSelf??(S3161). - An associated type, returned or thrown, that has no existential to be erased to: one constrained to a generic protocol, or to
Error(S3165). - An
asyncrequirement that returnsSelfor an associated type (S3161).
A member of an extension of a generic protocol, used on an any Validator<Int>, is its copy for the existential, whose Self is any Validator<Int>. A type that conforms to several instances of a generic protocol is an existential of each through that instance's members.
Generic Code Given an Existential#
Passing an existential to a generic function opens it too. The callee runs compiled once, with the value as its real type, so inside it, requirements that take Self are reachable:
protocol Shape: Equatable { fn doubled() -> Self}fn isFixedByDoubling<T: Shape>(_ x: T) -> Bool { return x.doubled() == x // '==' takes Self: fine here, T is one type}let s: any Shape = Square(side: 0)print(isFixedByDoubling(s)) // trueEach type parameter is opened from its own argument, so pair(a, b) for fn pair<A: P, B: Q>(_ a: A, _ b: B) opens both. A type parameter is opened when:
- it is constrained only to protocols that are not generic;
- exactly one parameter names it, as exactly
T, taken by value orinout(aninoutone changes the value inside the existential's box, which is first made its own); - the result, if it mentions
Tat all, is exactlyT, which is erased back to the existential.
Otherwise the callee's copy for the existential type itself runs, and in that copy a requirement taking Self is unreachable. That happens for a type parameter that two parameters name (the two existentials may hold different types), one a parameter names inside another type (T?, T[], (T) -> Int), one a result or error names inside another type (T?, T[], throws(T)), and one a where clause ties to another type.
Reflection#
Reflection describes a value or a type as the program runs: its fields, its cases, its methods, its attributes. Sable has two levels of it, and one level more for calling.
Mirror: Any Value, Read Only#
Mirror(of:) works on any value of any type, with nothing to declare. It is read only and cheap, and gives each field as text:
struct Temperature { var celsius: F64 var station: String}let reading = Temperature(celsius: 21.5, station: "Kew")let m = Mirror(of: reading)for field in m.fields { print("\(field.name): \(field.typeName) = \(field.value)")}celsius: F64 = 21.5station: String = KewA mirror also has the value's typeName, its kind, its caseName (for a union or enum value; none otherwise), a description, a count of its fields, and field(named:).
TypeInfo and @reflectable#
For a fuller description of a type — its methods, its conformances, its attributes — the type asks for it with @reflectable, which conforms it to the Reflectable protocol. Then TypeInfo.of describes it, given either the type or a value:
@reflectableclass Document { public var title: String var revision: Int = 0 public init(title: String) { self.title = title } public fn render() -> String => "# \(title)" public fn bump() { revision += 1 }}let info = TypeInfo.of(Document.self)for method in info.methods where method.isPublic { print(method.signature)}A TypeInfo has the type's name, kind, fields (each with name, typeName, isMutable, isPublic), methods (each with name, signature, parameter names and type names, returnTypeName, isStatic, isPublic, isMutating), cases for a union, and conformances. field(named:), method(named:) and conforms(to:) look one up by name.
To make a type from another package reflectable, write the conformance yourself: extension Point: Reflectable { }.
Calling by Reflection: @reflectable(callable)#
@reflectable(callable) goes one step further: it conforms the type to Callable, so that its public initialisers, methods and operators can be found by name and called with boxed (any Any) arguments:
@reflectable(callable)struct Counter { public var count: Int public init(from start: Int) { count = start } public mutating fn add(_ n: Int) -> Int { count += n return count }}var counter: any Any = try Counter.callable("init")!.call(1)let total = try Counter.callable("add")!.call(mutating: &counter, 2) as! Intprint(total) // 3print((counter as! Counter).count) // 3T.callableMembers() lists a type's members as CallableMembers, each with its name, signature, kind, parameterNames, parameterTypes and returnType (as Types), and whether it isMutating, isAsync or isThrowing. T.callable("name") finds the first with that name ("init" for an initialiser). On a Type, type(of: x).callableMembers and callable(_:) do the same for whatever x is.
A member is called with the form that fits it:
| Call | For |
|---|---|
call(args…), call(with:) |
An initialiser or a static member |
call(on: receiver, args…) |
An instance method |
call(mutating: &receiver, args…) |
A mutating method, changing the any Any in place |
callAsync(…) with the same forms, awaited |
A member whose call waits: an async one, or an actor's |
Each argument is taken out of its box as the parameter's type, and the receiver as the declaring type. If one isn't, the call throws a CallError (wrong argument count, wrong argument type, wrong receiver, a mutating member called with call(on:), and so on) instead of calling. What the member itself throws is thrown on. Default values are not filled in: every argument must be given.
Some members are listed but can't be called. Each has a refusal explaining why (isCallable is false): a member generic over its own type parameters; one with an inout or variadic parameter; one from an extension that applies only to some instances; an abstract class's initialiser; one whose parameter or result can't be boxed (a move-only type, a view, a function); and one isolated to an actor whose parameters or result aren't Sendable. @reflectable(callable) can't be written on a move-only type at all (S3080).
Only public members are callable, on purpose: what can be called by name could be called by any code, so access control holds without knowing who is asking.
Finding Types by Protocol: Plugins#
callableSubtypes() on a Type lists the @reflectable(callable) types that conform to it. That is how a program finds its plugins without a registry written by hand:
public protocol Filter { fn apply(_ text: String) throws -> String}@reflectable(callable)public struct Upper: Filter { public init() { } public fn apply(_ text: String) -> String => text.uppercased()}@reflectable(callable)public struct Repeat: Filter { let times: Int public init(_ times: Int) { self.times = times } public fn apply(_ text: String) -> String => text.repeated(times)}let filters: Type = (any Filter).selffor type in filters.callableSubtypes() { for member in type.callableMembers { print("\(type.name): \(member.signature)") }}let upper = try Upper.callable("init")!.call() as! any Filterprint(try upper.apply("sable")) // SABLEThe list is sorted by name. Only types that asked to be callable are in it — no linker flag, no scan of every type — and a generic type, which is no one type, never is. (A lookup of a type by an arbitrary string, Runtime.lookupType, does not exist; a program that loads plugins by name looks among callableSubtypes(), as examples/07-plugins.sb in the language repository does.)
Attributes You Define#
You can define your own attributes as structs that conform to Attribute, and read them back through reflection on a @reflectable type:
struct Route: Attribute { var path: String var method: String = "GET"}@reflectable@Route("/users", method: "POST")@Route("/people")struct UsersEndpoint { }for route in TypeInfo.of(UsersEndpoint.self).attributes(of: Route.self) { print("\(route.method) \(route.path)")}POST /usersGET /peopleAn attribute's arguments are checked as a call to one of the struct's initialisers would be, and must be constants: literals, enum cases, and arrays and tuples of them (S3511). A user attribute may be written on any declaration, and more than once; on a @reflectable type, attributes(of:) gives the values of one attribute type in the order they were written. hasAttribute(_:) checks for one by name.
What Reflection Costs#
Reflection is designed so that you pay only for what you ask for. A type that doesn't ask has no descriptor, no call thunks and nothing registered, so a program in which no type asks is byte for byte what it would have been without the feature.
At link time the compiler works out the reflection closure. The roots are the @reflectable types (and extension T: Reflectable conformances) and the types passed to TypeInfo.of with a statically known argument. The closure adds their field types, parameter and return types, generic arguments and conformances. Everything outside it carries no full description and is stripped.
Note
The design also calls for sable build --explain-reflection, which prints the closure as a tree with each type's cost in bytes, so that a type pulled in by accident is easy to spot. The driver doesn't have that flag yet.
A program, or a package's profile, can refuse reflection altogether with sable build --deny-reflection. Then Mirror, TypeInfo and @reflectable(callable) are errors (S3450).