simplify Peer Type Resolution #35197

Open
opened 2026-05-04 14:11:39 +02:00 by mlugg · 6 comments
Owner

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:

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!

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!
mlugg added this to the 0.18.0 milestone 2026-05-04 14:11:39 +02:00

I think this is a good direction, but breaks one important use case where the code just gets bloated:

var a: u32 = ...;
var b: ?u32 = ...;

if(a != b) return false; // operation clear
if(@as(?u32, a) != b) return false; // operation sus, would make me check decl of a
if(a orelse ~b == b) return false; // shorter than coercion

i have this pattern fairly often in my code and i'd be happy to keep it this way, as the auto-upgrade of non-optional to optional through PTR makes the code much less noisy

I think this is a good direction, but breaks one important use case where the code just gets bloated: ``` var a: u32 = ...; var b: ?u32 = ...; if(a != b) return false; // operation clear if(@as(?u32, a) != b) return false; // operation sus, would make me check decl of a if(a orelse ~b == b) return false; // shorter than coercion ``` i have this pattern fairly often in my code and i'd be happy to keep it this way, as the auto-upgrade of non-optional to optional through PTR makes the code much less noisy

I'm going to sound like a madperson here. And there are probably better cancelled projects to post this on but:

If everyone who encountered the previous submission wanted to remove PTR, even though it was going to break a bunch of code, then the reasoning "it's a bit too much breakage for too little benefit" is baffling to me. We want bees-in-bonnets, pedantic breaking shit! We want code to be broken! This is the Zig life!

Zig gets flak for being unreleased and slow iterations because you're actually changing core things - you might as well lean into it!! :) Rip it apart and put it together!

"seem to not be used too often", "this kind of [...] behavior is almost never used in real Zig code, and will not really be missed", this language is kinda avoiding the issue. When you're talking about complex behaviours that seem to cause unwanted results that you're trying to work around, including readability or complication, it tends to be either: the actual solution hasn't been formulated yet or there is some sort of code hickup elsewhere. I think the smartest move is to continue the removal, as long as you want to do it. I prefer the rejection to be an outright "I don't want to do it" than reasoning that it's going to break things and is pedantic. I live for pedantic.

I'm going to sound like a madperson here. And there are probably better cancelled projects to post this on but: If everyone who encountered the previous submission wanted to remove PTR, even though it was going to break a bunch of code, then the reasoning "it's a bit too much breakage for too little benefit" is baffling to me. We want bees-in-bonnets, pedantic breaking shit! We want code to be broken! This is the Zig life! Zig gets flak for being unreleased and slow iterations because you're actually changing core things - you might as well lean into it!! :) Rip it apart and put it together! "seem to not be used too often", "this kind of [...] behavior is almost never used in real Zig code, and will not really be missed", this language is kinda avoiding the issue. When you're talking about complex behaviours that seem to cause unwanted results that you're trying to work around, including readability or complication, it tends to be either: the actual solution hasn't been formulated yet or there is some sort of code hickup elsewhere. I think the smartest move is to continue the removal, as long as you want to do it. I prefer the rejection to be an outright "I don't want to do it" than reasoning that it's going to break things and is pedantic. I live for pedantic.
Contributor

I do think there's a lot to think about in this proposal, and I would like to write a more thorough comment after I've found the time to think about this deeply enough; as for now...

I see no mention of the interaction of noreturn and PTR - currently, PTR(T₁, T₂, ..., noreturn, ..., Tₙ₋₁, Tₙ) = PTR(T₁, T₂, ..., Tₙ₋₁, Tₙ), is the omission of this rule deliberate, or was it just forgotten?

I do think there's a lot to think about in this proposal, and I would like to write a more thorough comment after I've found the time to think about this deeply enough; as for now... I see no mention of the interaction of `noreturn` and PTR - currently, `PTR(T₁, T₂, ..., noreturn, ..., Tₙ₋₁, Tₙ) = PTR(T₁, T₂, ..., Tₙ₋₁, Tₙ)`, is the omission of this rule deliberate, or was it just forgotten?
Contributor

ref #36238

// decl-equal.zig
const Opt = enum(u8) {
    fast,
    safe,
    const declFast: Opt = .fast;
    const declSafe: Opt = .safe;
};
export fn f1(opt: Opt) bool {
    return opt == .safe;
}
export fn f2(opt: Opt) bool {
    return opt == .declSafe;
}

On 0.16.0 (and I assume master too), zig build-obj decl-equal.zig prints error: no field named 'declSafe' in enum 'decl-equal.Opt'. This surprises me: both cases use PTR (search "a == b" on the langref), but f1 succeeds while f2 fails to compile.

After this proposal, both f1 and f2 will fail to compile, right? I would hope they would instead both compile, by adding another exception:

  • If all peer types are equal, that type is returned.
  • If any peer types are @EnumLiteral(), exclude them from consideration. For example: MyType, @EnumLiteral() would return MyType.
  • ...
    (I don't love my wording here, but hopefully it's clear enough)

Without this exception, programmers would need to change if (mode == .fast) to if (mode == std.lang.Optimize.fast), right? Is that intended? Needing to type out fully-qualified enum names seems like a huge amount of extra friction, and for little gain.

I recognize that my proposed new exception would re-introduce some spooky-action-at-a-distance for const x = switch (y) { 1 => .fast, 2 => ..., ..., 25 => Opt.safe };, but this seems fine to me. (Or maybe the exception could be applied only when there are exactly two types, or some other variation.)

ref #36238 ```zig // decl-equal.zig const Opt = enum(u8) { fast, safe, const declFast: Opt = .fast; const declSafe: Opt = .safe; }; export fn f1(opt: Opt) bool { return opt == .safe; } export fn f2(opt: Opt) bool { return opt == .declSafe; } ``` On 0.16.0 (and I assume master too), `zig build-obj decl-equal.zig` prints `error: no field named 'declSafe' in enum 'decl-equal.Opt'`. This surprises me: both cases use PTR (search "a == b" on the [langref](https://ziglang.org/documentation/master/#Table-of-Operators)), but f1 succeeds while f2 fails to compile. After this proposal, both f1 and f2 will fail to compile, right? I would hope they would instead both compile, by adding another exception: - If all peer types are equal, that type is returned. - If any peer types are `@EnumLiteral()`, exclude them from consideration. For example: `MyType`, `@EnumLiteral()` would return `MyType`. - ... (I don't love my wording here, but hopefully it's clear enough) Without this exception, programmers would need to change `if (mode == .fast)` to `if (mode == std.lang.Optimize.fast)`, right? Is that intended? Needing to type out fully-qualified enum names seems like a huge amount of extra friction, and for little gain. I recognize that my proposed new exception would re-introduce some spooky-action-at-a-distance for `const x = switch (y) { 1 => .fast, 2 => ..., ..., 25 => Opt.safe };`, but this seems fine to me. (Or maybe the exception could be applied only when there are exactly two types, or some other variation.)
Contributor

Does your proposal includes PTR(T, noreturn) = T ?

It's useful for catch:

const x = arena.alloc(u8, 128) catch @panic("oom");

IIUC here Zig is doing PTR([]u8, noreturn)

Does your proposal includes `PTR(T, noreturn) = T` ? It's useful for catch: ``` const x = arena.alloc(u8, 128) catch @panic("oom"); ``` IIUC here Zig is doing `PTR([]u8, noreturn)`
Contributor

I realized PTR is actually a source of bug for me when dealing with arithmetic:

const sum: u32 = f() + g();

This snippet behave differently depending of the types returned by f and g.
If they return respectively u32 and u8, it works (PTR saves the day),
but if the two returns u8, the operation will panic (PTR shits the bed).

This behavior make the code hard to read: you need to know the type of all variables on a given line to understand what it does, even if this type is defined in a different file.

So I'm in favor of removing more PTR in favor of Result Types propagation, and propagate the u32 to both f() and g().

I realized PTR is actually a source of bug for me when dealing with arithmetic: ``` const sum: u32 = f() + g(); ``` This snippet behave differently depending of the types returned by `f` and `g`. If they return respectively `u32` and `u8`, it works (PTR saves the day), but if the two returns `u8`, the operation will panic (PTR shits the bed). This behavior make the code hard to read: you need to know the type of all variables on a given line to understand what it does, even if this type is defined in a different file. So I'm in favor of removing more PTR in favor of Result Types propagation, and propagate the `u32` to both `f()` and `g()`.
Sign in to join this conversation.
No milestone
No assignees
6 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
ziglang/zig#35197
No description provided.