From fa3649f71fdbcee9cbc3fc4b8b820803c92b607e Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Fri, 6 Feb 2015 12:39:19 -0800 Subject: [PATCH] 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 --- go/types/expr.go | 7 ++++++- go/types/testdata/expr3.src | 18 ++++++++++++++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/go/types/expr.go b/go/types/expr.go index 71b1b34e..67b91dad 100644 --- a/go/types/expr.go +++ b/go/types/expr.go @@ -1057,7 +1057,12 @@ func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind { break // cannot continue } // 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 x.mode != invalid { check.errorf(x.pos(), "cannot use %s as %s value in struct literal", x, etyp) diff --git a/go/types/testdata/expr3.src b/go/types/testdata/expr3.src index c370ce34..125a8503 100644 --- a/go/types/testdata/expr3.src +++ b/go/types/testdata/expr3.src @@ -4,6 +4,8 @@ package expr3 +import "time" + func indexes() { _ = 1 /* ERROR "cannot index" */ [0] _ = indexes /* ERROR "cannot index" */ [0] @@ -26,7 +28,7 @@ func indexes() { a0 = a[0] _ = a0 var a1 int32 - a1 = a /* ERROR "cannot assign" */ [1] + a1 = a /* ERROR "cannot assign" */ [1] _ = a1 _ = a[9] @@ -101,7 +103,6 @@ func indexes() { _, ok = m["bar"] _ = ok - var t string _ = t[- /* ERROR "negative" */ 1] _ = t[- /* ERROR "negative" */ 1 :] @@ -201,6 +202,15 @@ func struct_literals() { x int } _ = 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() { @@ -237,7 +247,7 @@ func array_literals() { a0 := [...]int{} assert(len(a0) == 0) - + a1 := [...]int{0, 1, 2} assert(len(a1) == 3) var a13 [3]int @@ -245,7 +255,7 @@ func array_literals() { a13 = a1 a14 = a1 /* ERROR "cannot assign" */ _, _ = a13, a14 - + a2 := [...]int{- /* ERROR "negative" */ 1: 0} _ = a2