-
Notifications
You must be signed in to change notification settings - Fork 18k
cmd/compile: constant bounds check inconsistency with type parameters #65417
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Really an inconsistency. By the current rule, a call to [edit]: a complete and a bit modified version: package main
import "unsafe"
func main() {
wontBuild(0) // comment on to compile
panics(0)
}
func wontBuild[T byte](t T) {
const str = "a"
_ = str[unsafe.Sizeof(t)]
}
func panics[T byte](t T) {
const str = "a"
_ = str[unsafe.Sizeof(t)+0]
} |
CC @golang/compiler |
Like @go101 said, this is working as intended. We could change the language spec such that |
So the inconsistency is a compiler dependent behavior? |
No. |
Thanks to @griesemer for pointing out I misread the issue description. Reopening. |
Thanks for the report. @griesemer and I agree both programs should panic. Running CC @cuonglm @cagedmantis in case either of you are interested in tackling this. It should be a small fix. |
I like that types2 is now considered user Go code 👍🏻 |
Change https://go.dev/cl/560575 mentions this issue: |
Go version
go version go1.21.6 windows/amd64
Output of
go env
in your module/workspace:What did you do?
This won't build, as it's known at compile time that the index is out of bounds of the constant string (playground):
This does build, though, even though the only difference is some arithmetic (+1) on the index, which is even more out of bounds. It instead produces a runtime panic (playground):
What did you see happen?
An inconsistency in how the unsafe.Sizeof() pseudo-constants are applied to static bounds checks.
What did you expect to see?
I'd expect neither version to build.
This was discovered when attempting to make an offset slice into a string constant, the offset depending on the passed type's size. In that particular case it would have panicked if a sufficiently large type was applied to the function, but no code ever used that large types with it. It would be nice if the compiler could ignore this error in case it's only ever fed smaller types. Probably difficult, though.
The text was updated successfully, but these errors were encountered: