cmd/protoc-gen-go: unexport implementation-specific XXX fields

We modify protoc-gen-go to stop generating exported XXX fields.
The unsafe implementation is unaffected by this change since unsafe
can access fields regardless of visibility. However, for the purego
implementation, we need to respect Go visibility rules as enforced
by the reflect package.

We work around this by generating a exporter function that given
a reference to the message and the field to export, returns a reference
to the unexported field value. This exporter function is protected by
a constant such that it is not linked into the final binary in non-purego
build environment.

Updates golang/protobuf#276

Change-Id: Idf5c1f158973fa1c61187ff41440acb21c5dac94
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/185141
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/internal/impl/pointer_reflect.go b/internal/impl/pointer_reflect.go
index 207c20b..6060154 100644
--- a/internal/impl/pointer_reflect.go
+++ b/internal/impl/pointer_reflect.go
@@ -11,26 +11,37 @@
 	"reflect"
 )
 
+const UnsafeEnabled = false
+
 // offset represents the offset to a struct field, accessible from a pointer.
 // The offset is the field index into a struct.
-type offset []int
+type offset struct {
+	index  int
+	export exporter
+}
 
 // offsetOf returns a field offset for the struct field.
-func offsetOf(f reflect.StructField) offset {
+func offsetOf(f reflect.StructField, x exporter) offset {
 	if len(f.Index) != 1 {
 		panic("embedded structs are not supported")
 	}
-	return f.Index
+	if f.PkgPath == "" {
+		return offset{index: f.Index[0]} // field is already exported
+	}
+	if x == nil {
+		panic("exporter must be provided for unexported field")
+	}
+	return offset{index: f.Index[0], export: x}
 }
 
 // IsValid reports whether the offset is valid.
-func (f offset) IsValid() bool { return f != nil }
+func (f offset) IsValid() bool { return f.index >= 0 }
 
 // invalidOffset is an invalid field offset.
-var invalidOffset = offset(nil)
+var invalidOffset = offset{index: -1}
 
 // zeroOffset is a noop when calling pointer.Apply.
-var zeroOffset = offset([]int{0})
+var zeroOffset = offset{index: 0}
 
 // pointer is an abstract representation of a pointer to a struct or field.
 type pointer struct{ v reflect.Value }
@@ -53,8 +64,12 @@
 // Apply adds an offset to the pointer to derive a new pointer
 // to a specified field. The current pointer must be pointing at a struct.
 func (p pointer) Apply(f offset) pointer {
-	// TODO: Handle unexported fields in an API that hides XXX fields?
-	return pointer{v: p.v.Elem().FieldByIndex(f).Addr()}
+	if f.export != nil {
+		if v := reflect.ValueOf(f.export(p.v.Interface(), f.index)); v.IsValid() {
+			return pointer{v: v}
+		}
+	}
+	return pointer{v: p.v.Elem().Field(f.index).Addr()}
 }
 
 // AsValueOf treats p as a pointer to an object of type t and returns the value.