/
json.go
111 lines (105 loc) · 2.38 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Copyright (c) 2017, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information
package main
import (
"encoding/json"
"go/ast"
"io"
"reflect"
"mvdan.cc/sh/syntax"
)
func writeJSON(w io.Writer, f *syntax.File, pretty bool) error {
val := reflect.ValueOf(f)
v, _ := recurse(val, val)
enc := json.NewEncoder(w)
if pretty {
enc.SetIndent("", "\t")
}
return enc.Encode(v)
}
func recurse(val, parent reflect.Value) (interface{}, string) {
switch val.Kind() {
case reflect.Ptr:
elem := val.Elem()
if !elem.IsValid() {
return nil, ""
}
return recurse(elem, val)
case reflect.Interface:
if val.IsNil() {
return nil, ""
}
v, tname := recurse(val.Elem(), val)
m := v.(map[string]interface{})
m["Type"] = tname
return m, ""
case reflect.Struct:
m := make(map[string]interface{}, val.NumField()+1)
addField := func(name string, v interface{}) {
switch x := v.(type) {
case bool:
if !x {
return
}
case string:
if x == "" {
return
}
case []interface{}:
if len(x) == 0 {
return
}
case nil:
return
}
m[name] = v
}
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
ftyp := typ.Field(i)
if ftyp.Type.Name() == "Pos" {
continue
}
if !ast.IsExported(ftyp.Name) {
continue
}
fval := val.Field(i)
v, _ := recurse(fval, fval)
switch ftyp.Name {
case "StmtList":
// inline their fields
m := v.(map[string]interface{})
for name, v := range m {
addField(name, v)
}
default:
addField(ftyp.Name, v)
}
}
// use the parent to find the method, as methods are
// defined on the pointer values.
if posMethod := parent.MethodByName("Pos"); posMethod.IsValid() {
m["Pos"] = translatePos(posMethod.Call(nil)[0])
}
if posMethod := parent.MethodByName("End"); posMethod.IsValid() {
m["End"] = translatePos(posMethod.Call(nil)[0])
}
return m, typ.Name()
case reflect.Slice:
l := make([]interface{}, val.Len())
for i := 0; i < val.Len(); i++ {
elem := val.Index(i)
l[i], _ = recurse(elem, elem)
}
return l, ""
default:
return val.Interface(), ""
}
}
func translatePos(val reflect.Value) map[string]interface{} {
return map[string]interface{}{
"Offset": val.MethodByName("Offset").Call(nil)[0].Uint(),
"Line": val.MethodByName("Line").Call(nil)[0].Uint(),
"Col": val.MethodByName("Col").Call(nil)[0].Uint(),
}
}