Skip to content

Commit

Permalink
eval: allow setting unexported struct fields
Browse files Browse the repository at this point in the history
This requires the implementation of reflect.StructOf be relaxed
to allow creating structs with unexported fields.
That is https://golang.org/cl/85661

For #170
  • Loading branch information
crawshaw committed Jan 2, 2018
1 parent 762453e commit 6e0c470
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
12 changes: 10 additions & 2 deletions eval/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"runtime/debug"
"strings"
"sync"
"unsafe"

"neugram.io/ng/eval/environ"
"neugram.io/ng/eval/gowrap"
Expand Down Expand Up @@ -1483,12 +1484,12 @@ func (p *Program) evalExpr(e expr.Expr) []reflect.Value {
for i, elem := range e.Values {
name := e.Keys[i].(*expr.Ident).Name
v := p.evalExprOne(elem)
st.FieldByName(name).Set(v)
setField(st.FieldByName(name), v)
}
} else {
for i, expr := range e.Values {
v := p.evalExprOne(expr)
st.Field(i).Set(v)
setField(st.Field(i), v)
}
}
return []reflect.Value{st}
Expand Down Expand Up @@ -1718,6 +1719,13 @@ func (p *Program) evalExpr(e expr.Expr) []reflect.Value {
panic(interpPanic{fmt.Errorf("TODO evalExpr(%s), %T", format.Expr(e), e)})
}

// setField sets a struct field to value.
// It sets the value even if the field is unexported.
func setField(field, value reflect.Value) {
fieldPtr := reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr()))
fieldPtr.Elem().Set(value)
}

func (p *Program) evalFuncLiteral(e *expr.FuncLiteral, recvt *tipe.Named) reflect.Value {
s := &Scope{
Parent: p.Universe,
Expand Down
21 changes: 21 additions & 0 deletions eval/testdata/unexported.ng
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Disabled until https://golang.org/cl/85661 is submitted.
print("OK")

/*
type t struct {
X string
Y int
}

v := t{
X: "string1",
Y: 1,
}

v.X = "string2"
v.Y = 2

if v == (t{"string2", 2}) {
print("OK")
}
*/

0 comments on commit 6e0c470

Please sign in to comment.