Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

syntax/typedjson: avoid MethodByName #961

Merged
merged 1 commit into from
Jan 7, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions syntax/typedjson/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,17 @@ func encodeValue(val reflect.Value) (reflect.Value, string) {
encTyp := reflect.StructOf(fields)
enc := reflect.New(encTyp).Elem()

// Pos methods are defined on struct pointer receivers.
for i, name := range [...]string{"Pos", "End"} {
if fn := val.Addr().MethodByName(name); fn.IsValid() {
encodePos(enc.Field(1+i), fn.Call(nil)[0])
}
// Node methods are defined on struct pointer receivers.
if node, _ := val.Addr().Interface().(syntax.Node); node != nil {
encodePos(enc.Field(1), node.Pos()) // posField
encodePos(enc.Field(2), node.End()) // endField
}
// Do the rest of the fields.
for i := 3; i < encTyp.NumField(); i++ {
ftyp := encTyp.Field(i)
fval := val.FieldByName(ftyp.Name)
if ftyp.Type == exportedPosType {
encodePos(enc.Field(i), fval)
encodePos(enc.Field(i), fval.Interface().(syntax.Pos))
} else {
encElem, _ := encodeValue(fval)
if encElem.IsValid() {
Expand Down Expand Up @@ -173,17 +172,17 @@ type exportedPos struct {
Offset, Line, Col uint
}

func encodePos(encPtr, val reflect.Value) {
if !val.MethodByName("IsValid").Call(nil)[0].Bool() {
func encodePos(encPtr reflect.Value, val syntax.Pos) {
if !val.IsValid() {
return
}
enc := reflect.New(exportedPosType.Elem())
encPtr.Set(enc)
enc = enc.Elem()

enc.Field(0).Set(val.MethodByName("Offset").Call(nil)[0])
enc.Field(1).Set(val.MethodByName("Line").Call(nil)[0])
enc.Field(2).Set(val.MethodByName("Col").Call(nil)[0])
enc.Field(0).SetUint(uint64(val.Offset()))
enc.Field(1).SetUint(uint64(val.Line()))
enc.Field(2).SetUint(uint64(val.Col()))
}

func decodePos(val reflect.Value, enc map[string]interface{}) {
Expand Down