go/types: don't permit implicit assignments to unexported struct fields via literals

Change-Id: I74eec172ba5a319f91c95e33b047f489dfce0c95
Reviewed-on: https://go-review.googlesource.com/4090
Reviewed-by: Alan Donovan <adonovan@google.com>
This commit is contained in:
Robert Griesemer 2015-02-06 12:39:19 -08:00
parent 9622599500
commit fa3649f71f
2 changed files with 20 additions and 5 deletions

View File

@ -1057,7 +1057,12 @@ func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind {
break // cannot continue break // cannot continue
} }
// i < len(fields) // i < len(fields)
etyp := fields[i].typ fld := fields[i]
if !fld.Exported() && fld.pkg != check.pkg {
check.errorf(x.pos(), "implicit assignment to unexported field %s in %s literal", fld.name, typ)
continue
}
etyp := fld.typ
if !check.assignment(x, etyp) { if !check.assignment(x, etyp) {
if x.mode != invalid { if x.mode != invalid {
check.errorf(x.pos(), "cannot use %s as %s value in struct literal", x, etyp) check.errorf(x.pos(), "cannot use %s as %s value in struct literal", x, etyp)

View File

@ -4,6 +4,8 @@
package expr3 package expr3
import "time"
func indexes() { func indexes() {
_ = 1 /* ERROR "cannot index" */ [0] _ = 1 /* ERROR "cannot index" */ [0]
_ = indexes /* ERROR "cannot index" */ [0] _ = indexes /* ERROR "cannot index" */ [0]
@ -26,7 +28,7 @@ func indexes() {
a0 = a[0] a0 = a[0]
_ = a0 _ = a0
var a1 int32 var a1 int32
a1 = a /* ERROR "cannot assign" */ [1] a1 = a /* ERROR "cannot assign" */ [1]
_ = a1 _ = a1
_ = a[9] _ = a[9]
@ -101,7 +103,6 @@ func indexes() {
_, ok = m["bar"] _, ok = m["bar"]
_ = ok _ = ok
var t string var t string
_ = t[- /* ERROR "negative" */ 1] _ = t[- /* ERROR "negative" */ 1]
_ = t[- /* ERROR "negative" */ 1 :] _ = t[- /* ERROR "negative" */ 1 :]
@ -201,6 +202,15 @@ func struct_literals() {
x int x int
} }
_ = P /* ERROR "invalid composite literal type" */ {} _ = P /* ERROR "invalid composite literal type" */ {}
// unexported fields
_ = time.Time{}
_ = time.Time{sec /* ERROR "unknown field" */ : 0}
_ = time.Time{
0 /* ERROR implicit assignment to unexported field sec in time.Time literal */,
0 /* ERROR implicit assignment */ ,
nil /* ERROR implicit assignment */ ,
}
} }
func array_literals() { func array_literals() {
@ -237,7 +247,7 @@ func array_literals() {
a0 := [...]int{} a0 := [...]int{}
assert(len(a0) == 0) assert(len(a0) == 0)
a1 := [...]int{0, 1, 2} a1 := [...]int{0, 1, 2}
assert(len(a1) == 3) assert(len(a1) == 3)
var a13 [3]int var a13 [3]int
@ -245,7 +255,7 @@ func array_literals() {
a13 = a1 a13 = a1
a14 = a1 /* ERROR "cannot assign" */ a14 = a1 /* ERROR "cannot assign" */
_, _ = a13, a14 _, _ = a13, a14
a2 := [...]int{- /* ERROR "negative" */ 1: 0} a2 := [...]int{- /* ERROR "negative" */ 1: 0}
_ = a2 _ = a2