-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathparser.go
350 lines (279 loc) · 6.59 KB
/
parser.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Package easyparser provides a Go module parser for AST
package easyparser
import (
"fmt"
"go/token"
"go/types"
"path/filepath"
"reflect"
tstypes "github.com/go-generalize/go-easyparser/types"
"github.com/go-utils/gopackages"
"golang.org/x/tools/go/packages"
)
// Parser is a Go module parser for TypeScript AST
type Parser struct {
pkgs []*packages.Package
types map[string]tstypes.Type
consts map[string][]constCandidate
basePackage string
Filter func(opt *FilterOpt) bool
Replacer func(t types.Type) tstypes.Type
// ForceMapNonNullable provides backward compatibility to interpret map as non-nullable
ForceMapNonNullable bool
// IgnoreOmittedJSONField is a flag to ignore omitted json fields
IgnoreOmittedJSONField bool
}
func getPackagePath(dir string) (root string, pkg string, err error) {
goModPath, err := gopackages.GetGoModPath(dir)
if err != nil {
return "", "", err
}
goModDir := filepath.Dir(goModPath)
mod, err := gopackages.GetGoModule(goModPath)
if err != nil {
return "", "", err
}
abs, err := filepath.Abs(dir)
if err != nil {
return "", "", err
}
rel, err := filepath.Rel(goModDir, abs)
if err != nil {
return "", "", err
}
return goModDir, filepath.Join(mod, "/"+rel), nil
}
// NewParser initializes a new Parser
func NewParser(dir string, filter func(*FilterOpt) bool) (*Parser, error) {
root, pkg, err := getPackagePath(dir)
if err != nil {
return nil, err
}
cfg := &packages.Config{
Mode: packages.NeedName |
packages.NeedCompiledGoFiles |
packages.NeedSyntax |
packages.NeedTypes |
packages.NeedTypesInfo,
Dir: root,
}
pkgs, err := packages.Load(cfg, pkg)
if err != nil {
return nil, err
}
if err := visitErrors(pkgs); err != nil {
return nil, err
}
return &Parser{
pkgs: pkgs,
basePackage: pkg,
Filter: filter,
}, nil
}
func (p *Parser) exported(t *types.Named, dep bool) bool {
opt := &FilterOpt{
BasePackage: false,
Package: t.Obj().Pkg().String(),
Name: t.Obj().Name(),
Exported: t.Obj().Exported(),
Dependency: dep,
}
packages.Visit(p.pkgs, nil, func(pkg *packages.Package) {
if pkg.Types.Scope() == t.Obj().Parent() {
opt.BasePackage = true
}
})
return p.Filter(opt)
}
func (p *Parser) isStruct(u types.Type) bool {
_, ok := u.(*types.Struct)
return ok
}
// Parse parses the Go module and returns ASTs
func (p *Parser) Parse() (res map[string]tstypes.Type, err error) {
defer func() {
if e := recover(); e != nil {
var ok bool
err, ok = e.(error)
if !ok {
err = fmt.Errorf("%+v", e)
}
}
}()
p.types = make(map[string]tstypes.Type)
p.consts = make(map[string][]constCandidate)
// parse const
packages.Visit(p.pkgs, nil, func(pkg *packages.Package) {
for _, obj := range pkg.TypesInfo.Defs {
if obj == nil {
continue
}
if obj.Parent() != pkg.Types.Scope() {
continue
}
switch v := obj.(type) {
case *types.Const: // const a = 1
p.parseConst(v)
}
}
})
// parse types
packages.Visit(p.pkgs, nil, func(pkg *packages.Package) {
for _, obj := range pkg.TypesInfo.Defs {
if obj == nil {
continue
}
if obj.Parent() != pkg.Types.Scope() {
continue
}
v, ok := obj.(*types.TypeName)
if !(ok && !v.IsAlias()) {
continue
}
t, ok := v.Type().(*types.Named)
if !ok {
continue
}
pp := &pkgParser{
Parser: p,
pkg: pkg.Types,
fset: pkg.Fset,
}
parsed := pp.parseType(t, false)
if parsed == nil {
continue
}
parsed.SetPackageName(pkg.Name)
}
})
p.sortConst()
return p.types, nil
}
// GetBasePackage returns a base module for the root package
func (p *Parser) GetBasePackage() string {
return p.basePackage
}
// pkgParser parses a types.Package
type pkgParser struct {
*Parser
pkg *types.Package
fset *token.FileSet
}
func (p *pkgParser) parseNamed(t *types.Named, dep bool) tstypes.Type {
if t.Obj().Type().Underlying().String() == "struct{wall uint64; ext int64; loc *time.Location}" {
return &tstypes.Date{}
}
if t.String() == "time.Time" {
return &tstypes.Date{}
}
exported := p.exported(t, dep)
if exported {
tt, ok := p.types[t.String()]
if ok {
return tt
}
} else if !dep {
return nil
}
// For recursive references to the same struct
var dummy *tstypes.Object
if exported && p.isStruct(t.Underlying()) {
dummy = &tstypes.Object{}
p.types[t.String()] = dummy
}
typ := p.parseType(t.Underlying(), true)
if dummy != nil {
//nolint
obj := typ.(*tstypes.Object)
dummy.Entries = obj.Entries
typ = dummy
}
if exported {
if typ, ok := typ.(tstypes.Enumerable); ok {
consts := p.consts[t.String()]
for i := range consts {
typ.AddCandidates(consts[i].Key, consts[i].Value)
}
}
if named, ok := typ.(tstypes.NamedType); ok {
named.SetName(t.String())
}
pos := p.fset.Position(t.Obj().Pos())
typ.SetPosition(&pos)
p.types[t.String()] = typ
}
return typ
}
func (p *pkgParser) parsePointer(u *types.Pointer) tstypes.Type {
return &tstypes.Nullable{
Inner: p.parseType(u.Elem(), true),
}
}
func (p *pkgParser) parseSlice(u *types.Slice) tstypes.Type {
if basic, ok := u.Elem().(*types.Basic); ok && basic.Kind() == types.Byte {
return &tstypes.Nullable{
Inner: &tstypes.String{},
}
}
return &tstypes.Nullable{
Inner: &tstypes.Array{
Inner: p.parseType(u.Elem(), true),
},
}
}
func (p *pkgParser) parseArray(u *types.Array) tstypes.Type {
return &tstypes.Array{
Inner: p.parseType(u.Elem(), true),
}
}
func (p *pkgParser) parseMap(u *types.Map) tstypes.Type {
keyType := p.parseType(u.Key(), true)
if !keyType.UsedAsMapKey() {
panic(keyType.String() + " cannot be used as key")
}
if p.ForceMapNonNullable {
return &tstypes.Map{
Key: keyType,
Value: p.parseType(u.Elem(), true),
}
}
return &tstypes.Nullable{
Inner: &tstypes.Map{
Key: keyType,
Value: p.parseType(u.Elem(), true),
},
}
}
func (p *pkgParser) parseInterface(_ *types.Interface) tstypes.Type {
return &tstypes.Any{}
}
func (p *pkgParser) parseType(u types.Type, dep bool) tstypes.Type {
var typ tstypes.Type
if p.Replacer != nil {
typ = p.Replacer(u)
if typ != nil {
return typ
}
}
switch u := u.(type) {
case *types.Named:
typ = p.parseNamed(u, dep)
case *types.Struct:
typ = p.parseStruct(u)
case *types.Basic:
typ = p.parseBasic(u)
case *types.Pointer:
typ = p.parsePointer(u)
case *types.Slice:
typ = p.parseSlice(u)
case *types.Array:
typ = p.parseArray(u)
case *types.Map:
typ = p.parseMap(u)
case *types.Interface:
typ = p.parseInterface(u)
default:
panic("unsupported named type: " + reflect.TypeOf(u).String())
}
return typ
}