-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathast.go
221 lines (191 loc) · 4.86 KB
/
ast.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package json2go
import (
"bytes"
"fmt"
"go/ast"
"go/printer"
"go/token"
"sort"
"strings"
)
// Printer settings - copy from gofmt.
// See: https://github.com/golang/go/blob/go1.15.5/src/cmd/gofmt/gofmt.go
const (
tabWidth = 8
printerMode = printer.UseSpaces | printer.TabIndent | printerNormalizeNumbers
// printerNormalizeNumbers means to canonicalize number literal prefixes
// and exponents while printing. See https://golang.org/doc/go1.13#gofmt.
//
// This value is defined in go/printer specifically for go/format and cmd/gofmt.
printerNormalizeNumbers = 1 << 30
)
func astMakeDecls(rootNodes []*node, opts options) []ast.Decl {
var decls []ast.Decl
for _, node := range rootNodes {
decls = append(decls, &ast.GenDecl{
Tok: token.TYPE,
Specs: []ast.Spec{
&ast.TypeSpec{
Name: ast.NewIdent(node.name),
Type: astTypeFromNode(node, opts),
},
},
})
}
return decls
}
func astPrintDecls(decls []ast.Decl) string {
file := &ast.File{
Name: ast.NewIdent("main"),
Decls: decls,
}
// Use go/printer with settings compatible with gofmt.
var buf bytes.Buffer
prn := printer.Config{Mode: printerMode, Tabwidth: tabWidth}
prn.Fprint(&buf, token.NewFileSet(), file)
// Remove go file header
repr := buf.String()
repr = strings.TrimPrefix(repr, "package main")
repr = strings.TrimSpace(repr)
return repr
}
func astTypeFromNode(n *node, opts options) ast.Expr {
var resultType ast.Expr
notRequiredAsPointer := true
allowPointer := true
switch n.t.(type) {
case nodeBoolType:
resultType = ast.NewIdent("bool")
case nodeIntType:
resultType = ast.NewIdent("int")
case nodeFloatType:
resultType = ast.NewIdent("float64")
case nodeStringType:
resultType = ast.NewIdent("string")
notRequiredAsPointer = opts.stringPointersWhenKeyMissing
case nodeTimeType:
resultType = astTypeFromTimeNode(n, opts)
if opts.timeAsStr {
notRequiredAsPointer = opts.stringPointersWhenKeyMissing
}
case nodeObjectType:
resultType = astStructTypeFromNode(n, opts)
case nodeExtractedType:
resultType = astTypeFromExtractedNode(n)
case nodeInterfaceType, nodeInitType:
resultType = newEmptyInterfaceExpr()
allowPointer = false
case nodeMapType:
resultType = astTypeFromMapNode(n, opts)
allowPointer = false
default:
panic(fmt.Sprintf("unknown type: %v", n.t))
}
if astTypeShouldBeAPointer(n, notRequiredAsPointer, allowPointer) {
resultType = &ast.StarExpr{
X: resultType,
}
}
for i := n.arrayLevel; i > 0; i-- {
resultType = &ast.ArrayType{
Elt: resultType,
}
}
return resultType
}
func astTypeFromTimeNode(n *node, opts options) ast.Expr {
var resultType ast.Expr
if opts.timeAsStr {
resultType = ast.NewIdent("string")
} else if n.root {
// We have to use type alias here to preserve "UnmarshalJSON" method from time type.
resultType = ast.NewIdent("= time.Time")
} else {
resultType = ast.NewIdent("time.Time")
}
return resultType
}
func astTypeFromMapNode(n *node, opts options) ast.Expr {
var ve ast.Expr
if len(n.children) == 0 {
ve = newEmptyInterfaceExpr()
} else {
ve = astTypeFromNode(n.children[0], opts)
}
return &ast.MapType{
Key: ast.NewIdent("string"),
Value: ve,
}
}
func astTypeFromExtractedNode(n *node) ast.Expr {
extName := n.externalTypeID
if extName == "" {
extName = n.name
}
return ast.NewIdent(extName)
}
func astStructTypeFromNode(n *node, opts options) *ast.StructType {
typeDesc := &ast.StructType{
Fields: &ast.FieldList{
List: []*ast.Field{},
},
}
// sort children by name
type nodeWithName struct {
name string
node *node
}
var sortedChildren []nodeWithName
for _, child := range n.children {
sortedChildren = append(sortedChildren, nodeWithName{
name: child.name,
node: child,
})
}
sort.Slice(sortedChildren, func(i, j int) bool {
return sortedChildren[i].name < sortedChildren[j].name
})
for _, child := range sortedChildren {
typeDesc.Fields.List = append(typeDesc.Fields.List, &ast.Field{
Names: []*ast.Ident{ast.NewIdent(child.name)},
Type: astTypeFromNode(child.node, opts),
Tag: astJSONTag(child.node.key, !child.node.required),
})
}
return typeDesc
}
func astJSONTag(key string, omitempty bool) *ast.BasicLit {
tag := fmt.Sprintf("%#v", key)
tag = strings.Trim(tag, `"`)
if omitempty {
tag = fmt.Sprintf("`json:\"%s,omitempty\"`", tag)
} else {
tag = fmt.Sprintf("`json:\"%s\"`", tag)
}
return &ast.BasicLit{
Value: tag,
}
}
func astTypeShouldBeAPointer(n *node, notRequiredAsPointer bool, allowPointer bool) bool {
if !allowPointer {
return false
}
if !n.root && n.arrayLevel == 0 {
if n.nullable || (!n.required && notRequiredAsPointer) {
return true
}
} else if n.arrayLevel > 0 {
if n.arrayWithNulls {
return true
}
}
return false
}
func newEmptyInterfaceExpr() ast.Expr {
return &ast.InterfaceType{
Methods: &ast.FieldList{
Opening: token.Pos(1),
Closing: token.Pos(2),
},
}
}