This proposal supersedes #22182. You might want to go and read that one first.
Background
Peer Type Resolution (PTR) is how the Zig compiler combines a set of many types into one type which all of the input types ("peer types") can coerce to. For instance, as it stands today, u8 and u16 peer resolve to u16, while *volatile [4:0]u8 and *const [7:0]u8 peer resolve to [:0]const volatile u8.
The main use case for PTR is combining the results of different branches of control flow. For instance, in the expression if (runtime_cond) a else b, the types of a and b are combined using Peer Type Resolution to determine the final type of the expression. PTR also has a few other use cases---if you want to learn about those, they are outlined by the (rejected) proposal #22182.
PTR can be useful, but the algorithm is quite complex, and it isn't always obvious to users how it will behave for a given set of input types. Aside from unnecessary language specification complexity, this also has the disadvantage that it discourages users from adding type annotations to expressions which may benefit from them in terms of code readability and auditability. In other words, this is a place where the Zig language could benefit from additional friction.
I'll talk a little more about why I am proposing these changes after we actually look at what the changes are...
Proposal
Limit the scope of PTR to a small, easy-to-intuit, and genuinely useful set of rules. Specifically, I suggest defining PTR as follows:
-
If all peer types are equal, that type is returned.
-
If all peer types are scalar numeric types (int, float, comptime_int, comptime_float), then the behavior matches today. This approximately means that the type with the "highest precision" is used, although runtime types are preferred over comptime_int/comptime_float.
Expand for a more precise formulation of the rule for numeric types...
Consider a partial order where:
comptime_int < {T | @typeInfo(T) == .int} < comptime_float < {T | @typeInfo(T) == .float}
- e.g.
comptime_int < {i16,u32,usize} < comptime_float < {f32,c_longdouble}
- for a "target-specified" integer type
T like usize, T < @Int(T_info.signedness, T_info.bits)
- e.g.
usize < u64 on 64-bit targets
- likewise,
c_longdouble < fN where N is the bit size of c_longdouble
- for two fixed-width (
uN/iN) int types Smol and Big, Smol <= Big iff Big can represent all values of Smol,
i.e. iff minInt(Big) <= minInt(Smol) and maxInt(Big) >= maxInt(Smol)
- for two fixed-width float types,
fN <= fM iff N <= M
Then, of the input types T1,T2,...,Tn, PTR will select the input type Tk where Tk <= Tm forall m=1,...,n. (If no such type exists, PTR fails. For instance, u16 and i8 do not peer-resolve, because neither type fully contains the other.)
This is almost like a subtyping relation, but it "prefers" fixed-width types over usize (etc) and over comptime_int/comptime_float.
This rule can and should be scrutinized in the future, but I am intentionally avoiding doing so in this proposal, particularly since it interacts heavily with undecided proposals like #3806.
-
If all peer types are vectors @Vector(n, T1), ..., @Vector(n, T2), then return @Vector(n, T) where T = PTR(T1, ..., Tn). Note that since the child type of a vector can only be a numeric type, this does not require the algorithm to recurse without bound (it only needs to check for the "scalar numeric type" case described above).
-
If all peer types are "slice-like" pointers (*[n]T or []T) with identical qualifiers and sentinels and with the same element type T, then return []T with the same qualifiers and sentinel.
-
Otherwise, PTR fails.
The last rule above (about "slice-like" pointers) is the strangest one, so deserves some justification. I've included this rule because I believe that expressions like if (cond) "string" else "longer string" comes up in reasonable code fairly often (particularly as an argument to std.Io.Writer.print), and that it would be annoying for this to require a type annotation. I admit this seems like an odd, and fairly arbitrary, carve-out, so I'm open to discussion there, and it might be worth experimenting with just removing that rule too.
It's difficult to exhaustively list the differences between my definition and the current one, because the current PTR algorithm is very complex (its implemenation in the compiler is over 1000 lines!)---but here are some interesting examples of resolutions which are supported on master but would fail under this proposal:
T + ?T => ?T
T + @TypeOf(null) => ?T (for non-nullable T)
error{A} + error{B} => error{ A, B }
- More generally,
E1 + E2 => E1 || E2
T + error{...} => error{...}!T (for non-error T)
struct { A, B } + struct { C, D } => struct { PTR(A,C), PTR(B,D) }
[n]A + @Vector(n, B) => @Vector(n, PTR(A,B))
Benefits
TL;DR: the behaviours being removed seem to not be used too often; lead to less readable code by discouraging type annotations; complicate the language specification and compiler implementation; and are a common source of behavior differences between runtime and comptime execution.
The set of rules I propose are designed so that the type returned by PTR is always "similar", in a sense, to all input types. For instance, if one input type is u32, then it is guaranteed that the result type will always be an integer or float type of some kind (rather than, for instance, an optional or error union). This can be a big improvement for code readability: when reading a variable binding const x = ..., it is usually critical for the reader to know the "type ID" of x (e.g. whether it is an optional), but perhaps a little less critical for them to know the exact type. On master, it is impossible to really determine the type ID of the result without reading all cases---for instance, a null literal in one switch prong could force the result to be an optional, regardless of what the other prongs are. The current behavior of PTR can also simply be too complex for a reader to correctly guess even if they know exactly what each peer type is.
This proposal also largely solves an issue I described in #22182. Consider the following snippet:
fnf(b:bool,x:u32)u32{constopt=if(b)nullelsex;if(opt)|x|returnx;return0;}
The important question here is: what type does opt have? If this function is called at runtime, then b is runtime-known, so the type of opt is determined by applying PTR to the types @TypeOf(null) and @TypeOf(x), resulting in the type ?u32. However, if f is called at compile time---or with CallModifier.always_inline with a comptime-known b---then b will be comptime-known, so the type of opt will not be determined through PTR. Instead, the type of opt will be either @TypeOf(null), or u32. In the latter case, this will lead to a compile error on the next line, because the operand to if is required to be an optional, not a u32! This kind of deviation between comptime and runtime behavior makes code less reusable. In this case, the behavior difference could have been avoided by simply adding a type annotation to opt. Under this proposal, because PTR can only return an optional type if all input types are optional types, PTR would fail anyway, so the user would be forced to include a type annotation on opt, preventing the issue.
Lastly, a nice side benefit of this proposal is implementation simplicity---though not a good justification in and of itself, this does perhaps add a little more weight to the other arguments! For instance, the proposed rules avoid the need for the PTR algorithm to recurse in any case. On master, running PTR on struct { A, B } and struct { C, D } requires recursively invoking PTR on two pairs of types. To the best of my knowledge, this kind of PTR behavior is almost never used in real Zig code, and will not really be missed!
This proposal supersedes [#22182](https://github.com/ziglang/zig/issues/22182). You might want to go and read that one first.
## Background
Peer Type Resolution (PTR) is how the Zig compiler combines a set of many types into one type which all of the input types ("peer types") can coerce to. For instance, as it stands today, `u8` and `u16` peer resolve to `u16`, while `*volatile [4:0]u8` and `*const [7:0]u8` peer resolve to `[:0]const volatile u8`.
The main use case for PTR is combining the results of different branches of control flow. For instance, in the expression `if (runtime_cond) a else b`, the types of `a` and `b` are combined using Peer Type Resolution to determine the final type of the expression. PTR also has a few other use cases---if you want to learn about those, they are outlined by the (rejected) proposal [#22182](https://github.com/ziglang/zig/issues/22182).
PTR can be useful, but the algorithm is quite complex, and it isn't always obvious to users how it will behave for a given set of input types. Aside from unnecessary language specification complexity, this also has the disadvantage that it discourages users from adding type annotations to expressions which may benefit from them in terms of code readability and auditability. In other words, this is a place where the Zig language could benefit from additional *friction*.
I'll talk a little more about why I am proposing these changes after we actually look at what the changes are...
## Proposal
Limit the scope of PTR to a small, easy-to-intuit, and *genuinely useful* set of rules. Specifically, I suggest defining PTR as follows:
* If all peer types are equal, that type is returned.
* If all peer types are scalar numeric types (int, float, comptime_int, comptime_float), then the behavior matches today. This approximately means that the type with the "highest precision" is used, although runtime types are preferred over `comptime_int`/`comptime_float`.
<details>
<summary>Expand for a more precise formulation of the rule for numeric types...</summary>
Consider a partial order where:
* `comptime_int < {T | @typeInfo(T) == .int} < comptime_float < {T | @typeInfo(T) == .float}`
* e.g. `comptime_int < {i16,u32,usize} < comptime_float < {f32,c_longdouble}`
* for a "target-specified" integer type `T` like `usize`, `T < @Int(T_info.signedness, T_info.bits)`
* e.g. `usize < u64` on 64-bit targets
* likewise, `c_longdouble < fN` where `N` is the bit size of `c_longdouble`
* for two fixed-width (`uN`/`iN`) int types `Smol` and `Big`, `Smol <= Big` iff `Big` can represent all values of `Smol`, \
i.e. iff `minInt(Big) <= minInt(Smol) and maxInt(Big) >= maxInt(Smol)`
* for two fixed-width float types, `fN <= fM` iff `N <= M`
<br>
Then, of the input types `T1,T2,...,Tn`, PTR will select the input type `Tk` where `Tk <= Tm forall m=1,...,n`. (If no such type exists, PTR fails. For instance, `u16` and `i8` do not peer-resolve, because neither type fully contains the other.)
This is *almost* like a subtyping relation, but it "prefers" fixed-width types over `usize` (etc) and over `comptime_int`/`comptime_float`.
This rule can and should be scrutinized in the future, but I am intentionally avoiding doing so in this proposal, particularly since it interacts heavily with undecided proposals like [#3806](https://github.com/ziglang/zig/issues/3806).
</details>
* If all peer types are vectors `@Vector(n, T1), ..., @Vector(n, T2)`, then return `@Vector(n, T)` where `T = PTR(T1, ..., Tn)`. Note that since the child type of a vector can only be a numeric type, this does not require the algorithm to recurse without bound (it only needs to check for the "scalar numeric type" case described above).
* If all peer types are "slice-like" pointers (`*[n]T` or `[]T`) with identical qualifiers and sentinels and with the same element type `T`, then return `[]T` with the same qualifiers and sentinel.
* Otherwise, PTR fails.
The last rule above (about "slice-like" pointers) is the strangest one, so deserves some justification. I've included this rule because I believe that expressions like `if (cond) "string" else "longer string"` comes up in reasonable code fairly often (particularly as an argument to `std.Io.Writer.print`), and that it would be annoying for this to require a type annotation. I admit this seems like an odd, and fairly arbitrary, carve-out, so I'm open to discussion there, and it might be worth experimenting with just removing that rule too.
It's difficult to exhaustively list the differences between my definition and the current one, because the current PTR algorithm is very complex (its implemenation in the compiler is over 1000 lines!)---but here are some interesting examples of resolutions which are supported on master but would fail under this proposal:
* `T` + `?T` => `?T`
* `T` + `@TypeOf(null)` => `?T` (for non-nullable `T`)
* `error{A}` + `error{B}` => `error{ A, B }`
* More generally, `E1` + `E2` => `E1 || E2`
* `T` + `error{...}` => `error{...}!T` (for non-error `T`)
* `struct { A, B }` + `struct { C, D }` => `struct { PTR(A,C), PTR(B,D) }`
* `[n]A` + `@Vector(n, B)` => `@Vector(n, PTR(A,B))`
## Benefits
**TL;DR:** the behaviours being removed seem to not be used too often; lead to less readable code by discouraging type annotations; complicate the language specification and compiler implementation; and are a common source of behavior differences between runtime and comptime execution.
---
The set of rules I propose are designed so that the type returned by PTR is always "similar", in a sense, to *all* input types. For instance, if one input type is `u32`, then it is guaranteed that the result type will always be an integer or float type of some kind (rather than, for instance, an optional or error union). This can be a big improvement for code readability: when reading a variable binding `const x = ...`, it is usually critical for the reader to know the "type ID" of `x` (e.g. whether it is an optional), but perhaps a little less critical for them to know the exact type. On master, it is impossible to really determine the type ID of the result without reading *all* cases---for instance, a `null` literal in one `switch` prong could force the result to be an optional, regardless of what the other prongs are. The current behavior of PTR can also simply be too complex for a reader to correctly guess *even if* they know exactly what each peer type is.
This proposal also largely solves an issue I described in [#22182](https://github.com/ziglang/zig/issues/22182). Consider the following snippet:
```zig
fn f(b: bool, x: u32) u32 {
const opt = if (b) null else x;
if (opt) |x| return x;
return 0;
}
```
The important question here is: what type does `opt` have? If this function is called at runtime, then `b` is runtime-known, so the type of `opt` is determined by applying PTR to the types `@TypeOf(null)` and `@TypeOf(x)`, resulting in the type `?u32`. However, if `f` is called at compile time---or with `CallModifier.always_inline` with a comptime-known `b`---then `b` will be comptime-known, so the type of `opt` will not be determined through PTR. Instead, the type of `opt` will be either `@TypeOf(null)`, or `u32`. In the latter case, this will lead to a compile error on the next line, because the operand to `if` is required to be an optional, not a `u32`! This kind of deviation between comptime and runtime behavior makes code less reusable. In this case, the behavior difference could have been avoided by simply adding a type annotation to `opt`. Under this proposal, because PTR can only return an optional type if all input types are optional types, PTR would fail anyway, so the user would be *forced* to include a type annotation on `opt`, preventing the issue.
Lastly, a nice side benefit of this proposal is implementation simplicity---though not a good justification in and of itself, this does perhaps add a little more weight to the other arguments! For instance, the proposed rules avoid the need for the PTR algorithm to recurse in any case. On master, running PTR on `struct { A, B }` and `struct { C, D }` requires recursively invoking PTR on two pairs of types. To the best of my knowledge, this kind of PTR behavior is almost never used in real Zig code, and will not really be missed!