Skip to content

Commit

Permalink
[dev.go2go] go/types: don't crash with unsafe.Alignof/Sizeof on a typ…
Browse files Browse the repository at this point in the history
…e parameter value

Report an error instead for now until we have a better idea.
(It's unclear what these operations should do as they are
defined to return a compile-time constant which we can't
know in general.)

Fixes #40301.

Change-Id: I22a991311de117bc00d52b67b4ce862ea09d855a
Reviewed-on: https://go-review.googlesource.com/c/go/+/244622
Reviewed-by: Robert Griesemer <gri@golang.org>
griesemer committed Jul 24, 2020
1 parent 64148d3 commit fad691c
Showing 4 changed files with 28 additions and 2 deletions.
8 changes: 8 additions & 0 deletions src/go/types/builtins.go
Original file line number Diff line number Diff line change
@@ -576,6 +576,10 @@ func (check *Checker) builtin(x *operand, call *ast.CallExpr, id builtinId) (_ b

case _Alignof:
// unsafe.Alignof(x T) uintptr
if x.typ.TypeParam() != nil {
check.invalidOp(call.Pos(), "unsafe.Alignof undefined for %s", x)
return
}
check.assignment(x, nil, "argument to unsafe.Alignof")
if x.mode == invalid {
return
@@ -633,6 +637,10 @@ func (check *Checker) builtin(x *operand, call *ast.CallExpr, id builtinId) (_ b

case _Sizeof:
// unsafe.Sizeof(x T) uintptr
if x.typ.TypeParam() != nil {
check.invalidOp(call.Pos(), "unsafe.Sizeof undefined for %s", x)
return
}
check.assignment(x, nil, "argument to unsafe.Sizeof")
if x.mode == invalid {
return
1 change: 1 addition & 0 deletions src/go/types/check_test.go
Original file line number Diff line number Diff line change
@@ -160,6 +160,7 @@ var tests = [][]string{
{"fixedbugs/issue39948.go2"},
{"fixedbugs/issue39976.go2"},
{"fixedbugs/issue39982.go2"},
{"fixedbugs/issue40301.go2"},
}

var fset = token.NewFileSet()
12 changes: 12 additions & 0 deletions src/go/types/fixedbugs/issue40301.go2
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package p

import "unsafe"

func _[type T](x T) {
_ = unsafe /* ERROR undefined */ .Alignof(x)
_ = unsafe /* ERROR undefined */ .Sizeof(x)
}
9 changes: 7 additions & 2 deletions src/go/types/operand.go
Original file line number Diff line number Diff line change
@@ -158,9 +158,14 @@ func operandString(x *operand, qf Qualifier) string {
// <typ>
if hasType {
if x.typ != Typ[Invalid] {
intro := " of type "
if isGeneric(x.typ) {
var intro string
switch {
case isGeneric(x.typ):
intro = " of generic type "
case x.typ.TypeParam() != nil:
intro = " of type parameter type "
default:
intro = " of type "
}
buf.WriteString(intro)
WriteType(&buf, x.typ, qf)

0 comments on commit fad691c

Please sign in to comment.