Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.Sign up
spec: order of evaluation vs panicking #23735
It's possible to write expressions that, depending on order of evaluation, may panic for different reasons. I think this is fine, but it might be worth mentioning or providing examples to make clearer / less surprising to users.
For example, consider:
Under cmd/compile, this snippet produces an "invalid memory address or nil pointer dereference" panic; whereas under gccgo, it produces an "index out of range" panic.
Another example is:
Both cmd/compile and gccgo produce a nil pointer dereference panic, but the Go spec appears to also permit division by zero.
The latter example is relevant to #23661, because of:
Today, the last statement is compiled into roughly:
It would be nice to optimize that to
But that would change the panic from "hash of unhashable type int" to "division by zero". This change appears valid under the Go spec, but it seems worth clarifying whether that's the case.
The Run-time panics section of the spec seems to imply to me that the nature of the panic is irrelevant, only whether there is one or not.
My reading of the spec would allow a panic with a "division by zero" error.
Currently, order desugars map assignment operations like m[k] op= r into m[k] = m[k] op r which in turn is transformed during walk into: tmp := *mapaccess(m, k) tmp = tmp op r *mapassign(m, k) = tmp However, this is suboptimal, as we could instead produce just: *mapassign(m, k) op= r One complication though is if "r == 0", then "m[k] /= r" and "m[k] %= r" will panic, and they need to do so *before* calling mapassign, otherwise we may insert a new zero-value element into the map. It would be spec compliant to just emit the "r != 0" check before calling mapassign (see #23735), but currently these checks aren't generated until SSA construction. For now, it's simpler to continue desugaring /= and %= into two map indexing operations. Fixes #23661. Change-Id: I46e3739d9adef10e92b46fdd78b88d5aabe68952 Reviewed-on: https://go-review.googlesource.com/91557 Run-TryBot: Matthew Dempsky <firstname.lastname@example.org> TryBot-Result: Gobot Gobot <email@example.com> Reviewed-by: Austin Clements <firstname.lastname@example.org>