simplify Peer Type Resolution #35197
Labels
No labels
abi/f32
abi/ilp32
abi/sf
accepted
arch/21k
arch/6502
arch/aarch64
arch/alpha
arch/amdgcn
arch/arc
arch/arc32
arch/arc64
arch/arm
arch/avr
arch/bfin
arch/bpf
arch/colossus
arch/cris
arch/csky
arch/dlx
arch/epiphany
arch/fr30
arch/frv
arch/hexagon
arch/hppa
arch/hppa64
arch/ia64
arch/kalimba
arch/kvx
arch/lanai
arch/lm32
arch/loongarch32
arch/loongarch64
arch/m32r
arch/m68k
arch/m88k
arch/mcore
arch/microblaze
arch/mips
arch/mips64
arch/mmix
arch/moxie
arch/mrisc32
arch/msp430
arch/nds32
arch/ns32k
arch/nvptx
arch/or1k
arch/powerpc
arch/powerpc64
arch/propeller
arch/riscv32
arch/riscv64
arch/rl78
arch/rx
arch/s390x
arch/sh
arch/sparc
arch/sparc64
arch/spirv
arch/spu
arch/tricore
arch/v850
arch/vax
arch/vc4
arch/ve
arch/wasm
arch/x86
arch/x86_64
arch/xcore
arch/xtensa
autodoc
backend/c
backend/llvm
backend/self-hosted
binutils
breaking
build system
debug info
docs
error message
frontend
fuzzing
incremental
lib/c
lib/compiler-rt
lib/cxx
lib/std
lib/tsan
lib/ubsan-rt
lib/unwind
linking
miscompilation
os/android
os/dragonfly
os/driverkit
os/emscripten
os/freebsd
os/fuchsia
os/haiku
os/hurd
os/illumos
os/ios
os/linux
os/maccatalyst
os/macos
os/managarm
os/netbsd
os/ohos
os/openbsd
os/plan9
os/redox
os/rtems
os/serenity
os/tvos
os/uefi
os/visionos
os/wasi
os/watchos
os/windows
proposal
release notes
testing
zig cc
zig fmt
zig reduce
bounty
bug
contributor-friendly
downstream
enhancement
infra
optimization
question
regression
upstream
use case
No assignees
6 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
ziglang/zig#35197
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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,
u8andu16peer resolve tou16, while*volatile [4:0]u8and*const [7:0]u8peer 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 ofaandbare 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}comptime_int < {i16,u32,usize} < comptime_float < {f32,c_longdouble}Tlikeusize,T < @Int(T_info.signedness, T_info.bits)usize < u64on 64-bit targetsc_longdouble < fNwhereNis the bit size ofc_longdoubleuN/iN) int typesSmolandBig,Smol <= BigiffBigcan represent all values ofSmol,i.e. iff
minInt(Big) <= minInt(Smol) and maxInt(Big) >= maxInt(Smol)fN <= fMiffN <= MThen, of the input types
T1,T2,...,Tn, PTR will select the input typeTkwhereTk <= Tm forall m=1,...,n. (If no such type exists, PTR fails. For instance,u16andi8do 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 overcomptime_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)whereT = 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]Tor[]T) with identical qualifiers and sentinels and with the same element typeT, then return[]Twith 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 tostd.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=>?TT+@TypeOf(null)=>?T(for non-nullableT)error{A}+error{B}=>error{ A, B }E1+E2=>E1 || E2T+error{...}=>error{...}!T(for non-errorT)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 bindingconst x = ..., it is usually critical for the reader to know the "type ID" ofx(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, anullliteral in oneswitchprong 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:
The important question here is: what type does
opthave? If this function is called at runtime, thenbis runtime-known, so the type ofoptis determined by applying PTR to the types@TypeOf(null)and@TypeOf(x), resulting in the type?u32. However, iffis called at compile time---or withCallModifier.always_inlinewith a comptime-knownb---thenbwill be comptime-known, so the type ofoptwill not be determined through PTR. Instead, the type ofoptwill be either@TypeOf(null), oru32. In the latter case, this will lead to a compile error on the next line, because the operand toifis required to be an optional, not au32! 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 toopt. 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 onopt, 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 }andstruct { 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!I think this is a good direction, but breaks one important use case where the code just gets bloated:
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 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
noreturnand 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?ref #36238
On 0.16.0 (and I assume master too),
zig build-obj decl-equal.zigprintserror: 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:
@EnumLiteral(), exclude them from consideration. For example:MyType,@EnumLiteral()would returnMyType.(I don't love my wording here, but hopefully it's clear enough)
Without this exception, programmers would need to change
if (mode == .fast)toif (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.)Does your proposal includes
PTR(T, noreturn) = T?It's useful for catch:
IIUC here Zig is doing
PTR([]u8, noreturn)I realized PTR is actually a source of bug for me when dealing with arithmetic:
This snippet behave differently depending of the types returned by
fandg.If they return respectively
u32andu8, 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
u32to bothf()andg().