-
Notifications
You must be signed in to change notification settings - Fork 0
/
tsdecls.go
364 lines (319 loc) · 8.01 KB
/
tsdecls.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package tsdecls
import (
_ "embed"
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"io"
"reflect"
"sort"
"strings"
"text/template"
"github.com/bobg/go-generics/maps"
"github.com/bobg/go-generics/set"
"github.com/fatih/camelcase"
"github.com/pkg/errors"
)
//go:embed tmpl
var tmplstr string
var tmpl = template.Must(template.New("").Parse(tmplstr))
// Write reads the Go package in dir,
// locates the given typename,
// and writes Typescript declarations for the type's eligible methods to w.
// The resulting Typescript methods send post requests to endpoints beginning with prefix.
func Write(w io.Writer, dir, typename, prefix string) error {
data := tsDecls{
Prefix: prefix,
ClassName: typename,
}
fset := token.NewFileSet()
astpkgs, err := parser.ParseDir(fset, dir, nil, 0)
if err != nil {
return errors.Wrapf(err, "loading %s", dir)
}
var astpkg *ast.Package
for name, p := range astpkgs {
if strings.HasSuffix(name, "_test") {
continue
}
if astpkg != nil {
return fmt.Errorf("found multiple packages in %s", dir)
}
astpkg = p
}
if astpkg == nil {
return fmt.Errorf("found no packages in %s", dir)
}
conf := &types.Config{Importer: importer.Default()}
pkg, err := conf.Check(astpkg.Name, fset, maps.Values(astpkg.Files), nil)
if err != nil {
return errors.Wrapf(err, "type-checking %s", dir)
}
scope := pkg.Scope()
if scope == nil {
return fmt.Errorf("scope == nil")
}
obj := scope.Lookup(typename)
if obj == nil {
return fmt.Errorf("obj == nil")
}
methods := make(map[string]methodInfo)
printed := set.New[string]()
for _, typ := range []types.Type{obj.Type(), types.NewPointer(obj.Type())} {
methodSet := types.NewMethodSet(typ)
for i := 0; i < methodSet.Len(); i++ {
method := methodSet.At(i)
fn, ok := method.Obj().(*types.Func)
if !ok {
continue
}
if !fn.Exported() {
continue
}
fname := fn.Name()
ftype := fn.Type()
sig, ok := ftype.(*types.Signature)
if !ok {
return fmt.Errorf("type of function %s is %T", fname, ftype)
}
var param, result *types.Var
params := sig.Params()
switch params.Len() {
case 0:
// do nothing
case 1:
p := params.At(0)
if types.TypeString(p.Type(), nil) != "context.Context" {
param = p
}
case 2:
if types.TypeString(params.At(0).Type(), nil) != "context.Context" {
continue // xxx skip this method
}
param = params.At(1)
default:
continue // xxx skip this method
}
if param != nil {
types, err := printNamedTypes(param.Type(), printed, nil)
if err != nil {
return err
}
data.Interfaces = append(data.Interfaces, types...)
}
results := sig.Results()
switch results.Len() {
case 0:
// do nothing
case 1:
r := results.At(0)
if types.TypeString(r.Type(), nil) != "error" {
result = r
}
case 2:
if types.TypeString(results.At(1).Type(), nil) != "error" {
continue // xxx skip this method
}
result = results.At(0)
default:
continue // xxx skip this method
}
if result != nil {
types, err := printNamedTypes(result.Type(), printed, nil)
if err != nil {
return err
}
data.Interfaces = append(data.Interfaces, types...)
}
methods[fname] = methodInfo{param: param, result: result}
}
}
names := maps.Keys(methods)
sort.Strings(names)
for _, name := range names {
info := methods[name]
m := tsMethod{SnakeName: toSnake(name)}
if info.param != nil {
m.ParamName = info.param.Name()
m.ReqType = printType(info.param.Type())
}
if info.result != nil {
m.RespType = printType(info.result.Type())
}
data.Methods = append(data.Methods, m)
}
return tmpl.Execute(w, data)
}
type methodInfo struct {
param, result *types.Var
}
type (
tsInterface struct {
Name string
Fields []tsField
}
tsField struct {
Name, Type string
}
tsMethod struct {
SnakeName, ParamName, ReqType, RespType string
}
tsDecls struct {
Prefix string
ClassName string
Interfaces []tsInterface
Methods []tsMethod
}
)
// This traverses typ recursively,
// printing TypeScript declarations for named types it finds.
// Depended-on types are printed earlier than the types depending on them.
func printNamedTypes(typ types.Type, printed set.Of[string], namer func(*types.Named) string) ([]tsInterface, error) {
key := types.TypeString(typ, nil)
switch key {
case "error", "context.Context":
return nil, nil
}
if printed.Has(key) {
return nil, nil
}
if namer == nil {
namer = defaultNamedName
}
switch typ := typ.(type) {
case *types.Array:
return printNamedTypes(typ.Elem(), printed, namer)
case *types.Basic:
return nil, nil
case *types.Chan:
return printNamedTypes(typ.Elem(), printed, namer)
// case *types.Interface:
case *types.Map:
types1, err := printNamedTypes(typ.Key(), printed, namer)
if err != nil {
return nil, err
}
types2, err := printNamedTypes(typ.Elem(), printed, namer)
if err != nil {
return nil, err
}
return append(types1, types2...), nil
case *types.Named:
printed.Add(key)
u := typ.Underlying()
result, err := printNamedTypes(u, printed, namer)
if err != nil {
return nil, err
}
if ptr, ok := u.(*types.Pointer); ok {
u = ptr.Elem()
}
switch u := u.(type) {
case *types.Struct:
intf := tsInterface{
Name: namer(typ),
}
for i := 0; i < u.NumFields(); i++ {
intf.Fields = append(intf.Fields, printStructField(u, i))
}
result = append(result, intf)
return result, nil
default:
return nil, fmt.Errorf("unexpected underlying type for %s: %T", key, u)
}
case *types.Pointer:
return printNamedTypes(typ.Elem(), printed, namer)
case *types.Signature:
var result []tsInterface
for i := 0; i < typ.Params().Len(); i++ {
v := typ.Params().At(i)
types, err := printNamedTypes(v.Type(), printed, namer)
if err != nil {
return nil, err
}
result = append(result, types...)
}
for i := 0; i < typ.Results().Len(); i++ {
v := typ.Results().At(i)
types, err := printNamedTypes(v.Type(), printed, namer)
if err != nil {
return nil, err
}
result = append(result, types...)
}
return result, nil
case *types.Slice:
return printNamedTypes(typ.Elem(), printed, namer)
case *types.Struct:
var result []tsInterface
for i := 0; i < typ.NumFields(); i++ {
v := typ.Field(i)
types, err := printNamedTypes(v.Type(), printed, namer)
if err != nil {
return nil, err
}
result = append(result, types...)
}
return result, nil
default:
return nil, fmt.Errorf("unexpected type %T", typ)
}
}
func printStructField(str *types.Struct, idx int) tsField {
var (
field = str.Field(idx)
name = field.Name()
tag = reflect.StructTag(str.Tag(idx))
)
if jsonTag, ok := tag.Lookup("json"); ok && jsonTag != "-" {
parts := strings.Split(jsonTag, ",")
name = parts[0]
}
return tsField{Name: name, Type: printType(field.Type())}
}
func defaultNamedName(n *types.Named) string {
return n.Obj().Name()
}
func printType(typ types.Type) string {
switch typ := typ.(type) {
case *types.Array:
return printType(typ.Elem()) + "[]"
case *types.Basic:
switch typ.Kind() {
case types.Bool:
return "boolean"
case types.Int, types.Int8, types.Int16, types.Int32, types.Int64:
return "number"
case types.Uint, types.Uint8, types.Uint16, types.Uint32, types.Uint64:
return "number"
case types.Float32, types.Float64:
return "number"
case types.String:
return "string"
}
case *types.Map:
return fmt.Sprintf("{[x: %s]: %s}", printType(typ.Key()), printType(typ.Elem()))
case *types.Named:
return typ.Obj().Name() // xxx
case *types.Pointer:
return printType(typ.Elem())
case *types.Slice:
el := typ.Elem()
if b, ok := el.Underlying().(*types.Basic); ok && b.Kind() == types.Byte {
return "string"
}
return printType(typ.Elem()) + "[]"
// xxx case *types.Struct:
}
return ""
}
func toSnake(inp string) string {
parts := camelcase.Split(inp)
for i := 0; i < len(parts); i++ {
parts[i] = strings.ToLower(parts[i])
}
return strings.Join(parts, "_")
}