gdp-wired 0.31.1 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +82 -6
  2. package/dist/core/c/reader.d.ts +86 -0
  3. package/dist/core/c/reader.js +860 -0
  4. package/dist/core/cli.d.ts +66 -0
  5. package/dist/core/cli.js +582 -0
  6. package/dist/core/dsl.d.ts +4 -2
  7. package/dist/core/dsl.js +22 -12
  8. package/dist/core/effect.d.ts +6 -4
  9. package/dist/core/effect.js +48 -10
  10. package/dist/core/ex/harness.exs +177 -0
  11. package/dist/core/ex/json.exs +46 -0
  12. package/dist/core/ex/reader.exs +462 -0
  13. package/dist/core/exists.d.ts +3 -0
  14. package/dist/core/exists.js +3 -1
  15. package/dist/core/extract-c.d.ts +35 -0
  16. package/dist/core/extract-c.js +424 -0
  17. package/dist/core/extract-check.js +27 -6
  18. package/dist/core/extract-ex.d.ts +16 -0
  19. package/dist/core/extract-ex.js +33 -0
  20. package/dist/core/extract-go-check.d.ts +28 -0
  21. package/dist/core/extract-go-check.js +639 -0
  22. package/dist/core/extract-go.d.ts +231 -0
  23. package/dist/core/extract-go.js +1166 -0
  24. package/dist/core/extract-jvm.d.ts +23 -0
  25. package/dist/core/extract-jvm.js +220 -0
  26. package/dist/core/extract-print.js +17 -7
  27. package/dist/core/extract-py.d.ts +15 -0
  28. package/dist/core/extract-py.js +31 -0
  29. package/dist/core/extract-rb.d.ts +17 -0
  30. package/dist/core/extract-rb.js +31 -0
  31. package/dist/core/extract-read.d.ts +20 -0
  32. package/dist/core/extract-read.js +46 -6
  33. package/dist/core/extract-rs.d.ts +12 -0
  34. package/dist/core/extract-rs.js +306 -0
  35. package/dist/core/extract-shapes.d.ts +2 -0
  36. package/dist/core/extract-shapes.js +6 -5
  37. package/dist/core/extract-step.d.ts +806 -0
  38. package/dist/core/extract-step.js +4141 -0
  39. package/dist/core/extract-swift.d.ts +27 -0
  40. package/dist/core/extract-swift.js +484 -0
  41. package/dist/core/extract-xstate.d.ts +10 -3
  42. package/dist/core/extract-xstate.js +50 -4
  43. package/dist/core/extract.d.ts +22 -3
  44. package/dist/core/extract.js +107 -18
  45. package/dist/core/go/go.mod +3 -0
  46. package/dist/core/go/reader.go +901 -0
  47. package/dist/core/infer.js +1770 -52
  48. package/dist/core/jvm/Harness.java +361 -0
  49. package/dist/core/jvm/JavaReader.java +825 -0
  50. package/dist/core/jvm/Jvm.java +332 -0
  51. package/dist/core/jvm/KtReader.java +960 -0
  52. package/dist/core/jvm/Rt.java +10 -0
  53. package/dist/core/laws.d.ts +66 -0
  54. package/dist/core/laws.js +522 -0
  55. package/dist/core/py/harness.py +328 -0
  56. package/dist/core/py/reader.py +447 -0
  57. package/dist/core/rb/harness.rb +233 -0
  58. package/dist/core/rb/reader.rb +375 -0
  59. package/dist/core/rs/Cargo.lock +108 -0
  60. package/dist/core/rs/Cargo.toml +14 -0
  61. package/dist/core/rs/src/main.rs +681 -0
  62. package/dist/core/swift/Harness.swift +124 -0
  63. package/dist/core/swift/Main.swift +34 -0
  64. package/dist/core/swift/Package.swift +13 -0
  65. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
  66. package/dist/kernel/epr.d.ts +35 -0
  67. package/dist/kernel/epr.js +1676 -0
  68. package/dist/kernel/prove.d.ts +44 -0
  69. package/dist/kernel/prove.js +657 -50
  70. package/dist/lean-kernel/emit.d.ts +1 -0
  71. package/dist/lean-kernel/emit.js +21 -4
  72. package/package.json +53 -2
@@ -0,0 +1,901 @@
1
+ // The Go front end's reader (core/extract-go.ts): one package's files parsed by go/parser and checked by go/types, and
2
+ // printed as JSON, each expression with its type and, where go/types folds it, its constant value. Nothing is decided
3
+ // here: the TypeScript side reads the JSON, executes a step symbolically and refuses what is outside its subset. An
4
+ // import outside the standard library is not loaded (its package is empty here), so whatever the code reads of it has
5
+ // an invalid type, which the TypeScript side refuses where it is read.
6
+ //
7
+ // go run . <dir> every .go file of the package in <dir> (its build constraints, not its tests)
8
+ // go run . <file.go>... the files given
9
+ package main
10
+
11
+ import (
12
+ "encoding/json"
13
+ "fmt"
14
+ "go/ast"
15
+ "go/build"
16
+ "go/constant"
17
+ "go/importer"
18
+ "go/parser"
19
+ "go/token"
20
+ "go/types"
21
+ "os"
22
+ "path/filepath"
23
+
24
+ "strings"
25
+ )
26
+
27
+ type J = map[string]any
28
+
29
+ var (
30
+ fset = token.NewFileSet()
31
+ info = &types.Info{Types: map[ast.Expr]types.TypeAndValue{}, Defs: map[*ast.Ident]types.Object{}, Uses: map[*ast.Ident]types.Object{}, Selections: map[*ast.SelectorExpr]*types.Selection{}, Implicits: map[ast.Node]types.Object{}}
32
+ tids = map[types.Type]int{}
33
+ ttab []J
34
+ pkg *types.Package
35
+ errors []string
36
+ )
37
+
38
+ func main() {
39
+ if len(os.Args) < 2 {
40
+ fmt.Fprintln(os.Stderr, "usage: reader <dir> | <file.go>...")
41
+ os.Exit(2)
42
+ }
43
+ var files []string
44
+ if st, err := os.Stat(os.Args[1]); err == nil && st.IsDir() {
45
+ bp, err := build.Default.ImportDir(os.Args[1], 0)
46
+ if err != nil {
47
+ fail(err)
48
+ }
49
+ for _, f := range bp.GoFiles {
50
+ files = append(files, filepath.Join(os.Args[1], f))
51
+ }
52
+ } else {
53
+ files = os.Args[1:]
54
+ }
55
+ var asts []*ast.File
56
+ for _, f := range files {
57
+ a, err := parser.ParseFile(fset, f, nil, parser.SkipObjectResolution)
58
+ if err != nil {
59
+ fail(err)
60
+ }
61
+ asts = append(asts, a)
62
+ }
63
+ std := importer.Default()
64
+ conf := types.Config{
65
+ Importer: importerFunc(func(path string) (*types.Package, error) {
66
+ if isStd(path) {
67
+ return std.Import(path)
68
+ }
69
+ // Another package outside the standard library: read from its source where `go list` finds it (its names'
70
+ // types, so its structs are data the step can read), its own imports empty (their names undefined, their
71
+ // types invalid); empty itself where it isn't found.
72
+ return foreignPackage(path, os.Args[1], std), nil
73
+ }),
74
+ Error: func(err error) { errors = append(errors, err.Error()) },
75
+ }
76
+ pkg, _ = conf.Check(asts[0].Name.Name, fset, asts, info)
77
+ out := J{"package": asts[0].Name.Name}
78
+ var fs, funcs, typs, consts, vars []J
79
+ for i, a := range asts {
80
+ imps := []J{}
81
+ for _, im := range a.Imports {
82
+ path := strings.Trim(im.Path.Value, `"`)
83
+ name := ""
84
+ if im.Name != nil {
85
+ name = im.Name.Name
86
+ }
87
+ imps = append(imps, J{"path": path, "name": name, "std": isStd(path)})
88
+ }
89
+ fs = append(fs, J{"name": filepath.Base(files[i]), "imports": imps})
90
+ for _, d := range a.Decls {
91
+ switch d := d.(type) {
92
+ case *ast.FuncDecl:
93
+ funcs = append(funcs, funcDecl(d))
94
+ case *ast.GenDecl:
95
+ for _, s := range d.Specs {
96
+ switch s := s.(type) {
97
+ case *ast.TypeSpec:
98
+ obj := info.Defs[s.Name]
99
+ typs = append(typs, J{"name": s.Name.Name, "t": tid(obj.Type()), "p": pos(s.Pos()), "span": span(s)})
100
+ case *ast.ValueSpec:
101
+ for _, n := range s.Names {
102
+ obj := info.Defs[n]
103
+ if obj == nil {
104
+ continue
105
+ }
106
+ if c, ok := obj.(*types.Const); ok {
107
+ consts = append(consts, J{"name": n.Name, "t": tid(c.Type()), "c": cval(c.Val()), "p": pos(n.Pos())})
108
+ } else {
109
+ vj := J{"name": n.Name, "t": tid(obj.Type()), "p": pos(n.Pos())}
110
+ if len(s.Values) == len(s.Names) {
111
+ for k, m := range s.Names {
112
+ if m == n {
113
+ vj["init"] = expr(s.Values[k])
114
+ }
115
+ }
116
+ }
117
+ vars = append(vars, vj)
118
+ }
119
+ }
120
+ }
121
+ }
122
+ }
123
+ }
124
+ }
125
+ out["files"], out["funcs"], out["types"], out["consts"], out["vars"], out["errors"] = fs, funcs, typs, consts, vars, errors
126
+ out["ttab"] = ttab
127
+ enc := json.NewEncoder(os.Stdout)
128
+ if err := enc.Encode(out); err != nil {
129
+ fail(err)
130
+ }
131
+ }
132
+
133
+ // Another package, one level deep: type-checked from its files with its own imports left empty, its errors (names of
134
+ // those imports, undefined) kept out of the package's own.
135
+ var foreign = map[string]*types.Package{}
136
+
137
+ func foreignPackage(path, from string, std types.Importer) *types.Package {
138
+ if p, ok := foreign[path]; ok {
139
+ return p
140
+ }
141
+ empty := func(p string) *types.Package {
142
+ q := types.NewPackage(p, guessName(p))
143
+ q.MarkComplete()
144
+ return q
145
+ }
146
+ foreign[path] = empty(path)
147
+ dir := from
148
+ if st, err := os.Stat(from); err != nil || !st.IsDir() {
149
+ dir = filepath.Dir(from)
150
+ }
151
+ pdir := localDir(path, dir)
152
+ if pdir == "" {
153
+ return foreign[path]
154
+ }
155
+ bp, err := build.Default.ImportDir(pdir, 0)
156
+ if err != nil || len(bp.GoFiles) == 0 {
157
+ return foreign[path]
158
+ }
159
+ var asts []*ast.File
160
+ for _, f := range bp.GoFiles {
161
+ a, err := parser.ParseFile(fset, filepath.Join(pdir, f), nil, parser.SkipObjectResolution)
162
+ if err != nil {
163
+ return foreign[path]
164
+ }
165
+ asts = append(asts, a)
166
+ }
167
+ conf := types.Config{
168
+ Importer: importerFunc(func(p string) (*types.Package, error) {
169
+ if isStd(p) {
170
+ return std.Import(p)
171
+ }
172
+ return empty(p), nil
173
+ }),
174
+ Error: func(error) {},
175
+ }
176
+ tp, _ := conf.Check(path, fset, asts, nil)
177
+ if tp == nil {
178
+ return foreign[path]
179
+ }
180
+ foreign[path] = tp
181
+ return tp
182
+ }
183
+
184
+ // Where a package of the module the code is in lives: under the module's root, or under a local replace of its go.mod
185
+ // (Kubernetes's staging modules). Another module's (downloaded) is not read: "".
186
+ func localDir(path, from string) string {
187
+ root := from
188
+ for {
189
+ if _, err := os.Stat(filepath.Join(root, "go.mod")); err == nil {
190
+ break
191
+ }
192
+ up := filepath.Dir(root)
193
+ if up == root {
194
+ return ""
195
+ }
196
+ root = up
197
+ }
198
+ data, err := os.ReadFile(filepath.Join(root, "go.mod"))
199
+ if err != nil {
200
+ return ""
201
+ }
202
+ under := func(base, mod string) string {
203
+ if path == mod {
204
+ return base
205
+ }
206
+ if strings.HasPrefix(path, mod+"/") {
207
+ return filepath.Join(base, filepath.FromSlash(path[len(mod)+1:]))
208
+ }
209
+ return ""
210
+ }
211
+ inReplace := false
212
+ for _, line := range strings.Split(string(data), "\n") {
213
+ f := strings.Fields(strings.SplitN(line, "//", 2)[0])
214
+ switch {
215
+ case len(f) == 2 && f[0] == "module":
216
+ if d := under(root, strings.Trim(f[1], `"`)); d != "" {
217
+ return existing(d)
218
+ }
219
+ case len(f) >= 2 && f[0] == "replace" && f[1] == "(":
220
+ inReplace = true
221
+ case inReplace && len(f) == 1 && f[0] == ")":
222
+ inReplace = false
223
+ default:
224
+ if len(f) > 0 && f[0] == "replace" {
225
+ f = f[1:]
226
+ } else if !inReplace {
227
+ continue
228
+ }
229
+ // a [v] => ./local [v]
230
+ for i, x := range f {
231
+ if x == "=>" && i+1 < len(f) && i >= 1 && (strings.HasPrefix(f[i+1], "./") || strings.HasPrefix(f[i+1], "../")) {
232
+ if d := under(filepath.Join(root, filepath.FromSlash(f[i+1])), f[0]); d != "" {
233
+ return existing(d)
234
+ }
235
+ }
236
+ }
237
+ }
238
+ }
239
+ return ""
240
+ }
241
+ func existing(d string) string {
242
+ if st, err := os.Stat(d); err == nil && st.IsDir() {
243
+ return d
244
+ }
245
+ return ""
246
+ }
247
+
248
+ type importerFunc func(string) (*types.Package, error)
249
+
250
+ func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }
251
+
252
+ // The name the check's harness imports another package by (two packages may share a name: k8s.io/api/rbac/v1 and
253
+ // k8s.io/apimachinery/pkg/apis/meta/v1 are both v1). core/extract-go-check.ts's alias is the same.
254
+ func alias(path string) string {
255
+ b := []byte("gdp_")
256
+ for _, c := range []byte(path) {
257
+ if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' {
258
+ b = append(b, c)
259
+ } else {
260
+ b = append(b, '_')
261
+ }
262
+ }
263
+ return string(b)
264
+ }
265
+ func isStd(path string) bool {
266
+ first := strings.SplitN(path, "/", 2)[0]
267
+ return !strings.Contains(first, ".") && path != "C"
268
+ }
269
+ func guessName(path string) string {
270
+ last := path[strings.LastIndex(path, "/")+1:]
271
+ if strings.HasPrefix(last, "v") && len(last) > 1 && strings.Trim(last[1:], "0123456789") == "" && strings.Contains(path, "/") {
272
+ rest := path[:strings.LastIndex(path, "/")]
273
+ last = rest[strings.LastIndex(rest, "/")+1:]
274
+ }
275
+ last = strings.TrimPrefix(last, "go-")
276
+ if i := strings.IndexAny(last, ".-"); i >= 0 {
277
+ last = last[:i]
278
+ }
279
+ return last
280
+ }
281
+ func fail(err error) {
282
+ fmt.Fprintln(os.Stderr, err)
283
+ os.Exit(1)
284
+ }
285
+
286
+ // --- positions ------------------------------------------------------------------------------------------------------
287
+ func pos(p token.Pos) string {
288
+ if !p.IsValid() {
289
+ return ""
290
+ }
291
+ q := fset.Position(p)
292
+ return fmt.Sprintf("%s:%d:%d", filepath.Base(q.Filename), q.Line, q.Column)
293
+ }
294
+ func span(n ast.Node) []int { return []int{fset.Position(n.Pos()).Line, fset.Position(n.End()).Line} }
295
+
296
+ // --- types: a table, each type once (named types by name, so recursive ones end) -----------------------------------
297
+ func tid(t types.Type) int {
298
+ if t == nil {
299
+ t = types.Typ[types.Invalid]
300
+ }
301
+ if i, ok := tids[t]; ok {
302
+ return i
303
+ }
304
+ // Identical types share an entry (types.Identical), so the TypeScript side compares them by number.
305
+ for u, i := range tids {
306
+ if types.Identical(u, t) {
307
+ tids[t] = i
308
+ return i
309
+ }
310
+ }
311
+ i := len(ttab)
312
+ tids[t] = i
313
+ ttab = append(ttab, nil)
314
+ d := describe(t)
315
+ // The type as Go writes it in the package (the check's harness declares values of it).
316
+ d["go"] = types.TypeString(t, func(p *types.Package) string {
317
+ if p == pkg {
318
+ return ""
319
+ }
320
+ if !isStd(p.Path()) {
321
+ return alias(p.Path())
322
+ }
323
+ return p.Name()
324
+ })
325
+ ttab[i] = d
326
+ return i
327
+ }
328
+
329
+ func describe(t types.Type) J {
330
+ switch t := t.(type) {
331
+ case *types.Basic:
332
+ return basic(t, "", "")
333
+ case *types.Named:
334
+ obj := t.Obj()
335
+ path := ""
336
+ if obj.Pkg() != nil {
337
+ path = obj.Pkg().Path()
338
+ }
339
+ own := obj.Pkg() == pkg
340
+ j := J{"name": obj.Name(), "pkg": path, "own": own}
341
+ if t.TypeParams().Len() > 0 {
342
+ j["generic"] = true
343
+ }
344
+ if t.TypeArgs().Len() > 0 {
345
+ args := []int{}
346
+ for i := 0; i < t.TypeArgs().Len(); i++ {
347
+ args = append(args, tid(t.TypeArgs().At(i)))
348
+ }
349
+ j["args"] = args
350
+ }
351
+ // Another package's named type: opaque, but an integer, boolean or string one keeps its basic kind
352
+ // (time.Duration is an int64), and math/big.Int, error and the like are recognized by name.
353
+ if !own {
354
+ if b, ok := t.Underlying().(*types.Basic); ok {
355
+ for k, v := range basic(b, obj.Name(), path) {
356
+ j[k] = v
357
+ }
358
+ return j
359
+ }
360
+ j["k"] = "ext"
361
+ if _, ok := t.Underlying().(*types.Interface); ok {
362
+ j["iface"] = true
363
+ }
364
+ // Another package's struct (outside the standard library): its fields too, as data. Its methods stay
365
+ // another package's code.
366
+ if st, ok := t.Underlying().(*types.Struct); ok && strings.Contains(strings.Split(path, "/")[0], ".") {
367
+ fields := []J{}
368
+ for i := 0; i < st.NumFields(); i++ {
369
+ f := st.Field(i)
370
+ fields = append(fields, J{"name": f.Name(), "t": tid(f.Type()), "embedded": f.Embedded(), "exported": f.Exported()})
371
+ }
372
+ j["xfields"] = fields
373
+ }
374
+ if obj.Name() == "error" && path == "" {
375
+ j["k"] = "error"
376
+ }
377
+ return j
378
+ }
379
+ u := describe(t.Underlying())
380
+ for k, v := range u {
381
+ if k != "name" && k != "pkg" {
382
+ j[k] = v
383
+ }
384
+ }
385
+ methods := []J{}
386
+ for i := 0; i < t.NumMethods(); i++ {
387
+ m := t.Method(i)
388
+ sig := m.Type().(*types.Signature)
389
+ _, ptr := sig.Recv().Type().(*types.Pointer)
390
+ methods = append(methods, J{"name": m.Name(), "ptr": ptr})
391
+ }
392
+ j["methods"] = methods
393
+ return j
394
+ case *types.Pointer:
395
+ return J{"k": "ptr", "elem": tid(t.Elem())}
396
+ case *types.Struct:
397
+ fields := []J{}
398
+ for i := 0; i < t.NumFields(); i++ {
399
+ f := t.Field(i)
400
+ fields = append(fields, J{"name": f.Name(), "t": tid(f.Type()), "embedded": f.Embedded(), "exported": f.Exported()})
401
+ }
402
+ return J{"k": "struct", "fields": fields}
403
+ case *types.Map:
404
+ return J{"k": "map", "key": tid(t.Key()), "elem": tid(t.Elem())}
405
+ case *types.Slice:
406
+ return J{"k": "slice", "elem": tid(t.Elem())}
407
+ case *types.Array:
408
+ return J{"k": "array", "len": t.Len(), "elem": tid(t.Elem())}
409
+ case *types.Signature:
410
+ ps, rs := []int{}, []int{}
411
+ for i := 0; i < t.Params().Len(); i++ {
412
+ ps = append(ps, tid(t.Params().At(i).Type()))
413
+ }
414
+ for i := 0; i < t.Results().Len(); i++ {
415
+ rs = append(rs, tid(t.Results().At(i).Type()))
416
+ }
417
+ return J{"k": "func", "params": ps, "results": rs, "variadic": t.Variadic()}
418
+ case *types.Tuple:
419
+ es := []int{}
420
+ for i := 0; i < t.Len(); i++ {
421
+ es = append(es, tid(t.At(i).Type()))
422
+ }
423
+ return J{"k": "tuple", "elems": es}
424
+ case *types.Interface:
425
+ return J{"k": "iface", "empty": t.Empty()}
426
+ case *types.TypeParam:
427
+ return J{"k": "typeparam", "name": t.Obj().Name()}
428
+ case *types.Chan:
429
+ return J{"k": "chan"}
430
+ case *types.Alias:
431
+ return describe(types.Unalias(t))
432
+ }
433
+ return J{"k": "other", "s": t.String()}
434
+ }
435
+ func basic(b *types.Basic, name, path string) J {
436
+ j := J{}
437
+ if name != "" {
438
+ j["name"], j["pkg"] = name, path
439
+ }
440
+ info := b.Info()
441
+ switch {
442
+ case b.Kind() == types.Invalid:
443
+ j["k"] = "invalid"
444
+ case b.Kind() == types.UntypedNil:
445
+ j["k"] = "nil"
446
+ case info&types.IsBoolean != 0:
447
+ j["k"] = "bool"
448
+ case info&types.IsString != 0:
449
+ j["k"] = "string"
450
+ case info&types.IsInteger != 0:
451
+ j["k"] = "int"
452
+ j["signed"] = info&types.IsUnsigned == 0
453
+ j["bits"] = map[types.BasicKind]int{types.Int: 64, types.Int8: 8, types.Int16: 16, types.Int32: 32, types.Int64: 64, types.Uint: 64, types.Uint8: 8, types.Uint16: 16, types.Uint32: 32, types.Uint64: 64, types.Uintptr: 64, types.UntypedInt: 0, types.UntypedRune: 32}[b.Kind()]
454
+ if info&types.IsUntyped != 0 {
455
+ j["untyped"] = true
456
+ }
457
+ case info&types.IsFloat != 0:
458
+ j["k"] = "float"
459
+ case info&types.IsComplex != 0:
460
+ j["k"] = "complex"
461
+ default:
462
+ j["k"] = "other"
463
+ j["s"] = b.String()
464
+ }
465
+ if b.Kind() == types.UnsafePointer {
466
+ j["k"] = "other"
467
+ }
468
+ return j
469
+ }
470
+ func cval(v constant.Value) any {
471
+ if v == nil {
472
+ return nil
473
+ }
474
+ switch v.Kind() {
475
+ case constant.Int:
476
+ return J{"int": v.ExactString()}
477
+ case constant.Bool:
478
+ return J{"bool": constant.BoolVal(v)}
479
+ case constant.String:
480
+ return J{"str": constant.StringVal(v)}
481
+ case constant.Float:
482
+ // A float constant that is a whole number is still a float (its type says so); its text is kept for the reason.
483
+ return J{"float": v.ExactString()}
484
+ }
485
+ return J{"other": v.String()}
486
+ }
487
+
488
+ // --- declarations ---------------------------------------------------------------------------------------------------
489
+ func funcDecl(d *ast.FuncDecl) J {
490
+ j := J{"name": d.Name.Name, "p": pos(d.Pos()), "span": span(d)}
491
+ if d.Recv != nil && len(d.Recv.List) == 1 {
492
+ r := d.Recv.List[0]
493
+ t := info.Types[r.Type].Type
494
+ _, ptr := t.(*types.Pointer)
495
+ base := t
496
+ if ptr {
497
+ base = t.(*types.Pointer).Elem()
498
+ }
499
+ name := ""
500
+ if n, ok := base.(*types.Named); ok {
501
+ name = n.Obj().Name()
502
+ }
503
+ rj := J{"t": tid(t), "ptr": ptr, "type": name}
504
+ if len(r.Names) == 1 && r.Names[0].Name != "_" {
505
+ rj["name"], rj["id"] = r.Names[0].Name, objID(info.Defs[r.Names[0]])
506
+ }
507
+ j["recv"] = rj
508
+ }
509
+ if d.Type.TypeParams != nil && d.Type.TypeParams.NumFields() > 0 {
510
+ j["generic"] = true
511
+ }
512
+ j["params"] = fields(d.Type.Params)
513
+ j["results"] = fields(d.Type.Results)
514
+ if d.Body != nil {
515
+ j["body"] = block(d.Body)
516
+ }
517
+ return j
518
+ }
519
+ func fields(fl *ast.FieldList) []J {
520
+ out := []J{}
521
+ if fl == nil {
522
+ return out
523
+ }
524
+ for _, f := range fl.List {
525
+ t := tid(info.Types[f.Type].Type)
526
+ _, variadic := f.Type.(*ast.Ellipsis)
527
+ if len(f.Names) == 0 {
528
+ out = append(out, J{"t": t, "variadic": variadic})
529
+ }
530
+ for _, n := range f.Names {
531
+ out = append(out, J{"name": n.Name, "id": objID(info.Defs[n]), "t": tid(info.Defs[n].Type()), "variadic": variadic, "ts": types.ExprString(f.Type)})
532
+ }
533
+ }
534
+ return out
535
+ }
536
+
537
+ // An object's identity: where it is declared (so the TypeScript side needs no scopes of its own).
538
+ func objID(o types.Object) string {
539
+ if o == nil {
540
+ return ""
541
+ }
542
+ if o.Pkg() != nil && o.Pkg() != pkg {
543
+ return o.Pkg().Path() + "." + o.Name()
544
+ }
545
+ if o.Parent() == pkg.Scope() || o.Parent() == nil {
546
+ if fn, ok := o.(*types.Func); ok {
547
+ if r := fn.Type().(*types.Signature).Recv(); r != nil {
548
+ return "method:" + o.Name()
549
+ }
550
+ }
551
+ return "pkg:" + o.Name()
552
+ }
553
+ q := fset.Position(o.Pos())
554
+ return fmt.Sprintf("%s:%d", filepath.Base(q.Filename), q.Offset)
555
+ }
556
+
557
+ // --- statements -----------------------------------------------------------------------------------------------------
558
+ func block(b *ast.BlockStmt) []J {
559
+ out := []J{}
560
+ if b == nil {
561
+ return out
562
+ }
563
+ for _, s := range b.List {
564
+ out = append(out, stmt(s))
565
+ }
566
+ return out
567
+ }
568
+ func stmt(s ast.Stmt) J {
569
+ j := J{"p": pos(s.Pos())}
570
+ switch s := s.(type) {
571
+ case *ast.BlockStmt:
572
+ j["s"], j["b"] = "block", block(s)
573
+ case *ast.ExprStmt:
574
+ j["s"], j["x"] = "expr", expr(s.X)
575
+ case *ast.AssignStmt:
576
+ j["s"], j["op"], j["l"], j["r"] = "assign", s.Tok.String(), exprs(s.Lhs), exprs(s.Rhs)
577
+ case *ast.IncDecStmt:
578
+ j["s"], j["op"], j["x"] = "incdec", s.Tok.String(), expr(s.X)
579
+ case *ast.IfStmt:
580
+ j["s"], j["c"], j["then"] = "if", expr(s.Cond), block(s.Body)
581
+ if s.Init != nil {
582
+ j["init"] = stmt(s.Init)
583
+ }
584
+ if s.Else != nil {
585
+ j["else"] = stmt(s.Else)
586
+ }
587
+ case *ast.SwitchStmt:
588
+ j["s"] = "switch"
589
+ if s.Init != nil {
590
+ j["init"] = stmt(s.Init)
591
+ }
592
+ if s.Tag != nil {
593
+ j["tag"] = expr(s.Tag)
594
+ }
595
+ cases := []J{}
596
+ for _, c := range s.Body.List {
597
+ cc := c.(*ast.CaseClause)
598
+ cj := J{"b": []J{}, "p": pos(cc.Pos())}
599
+ if cc.List == nil {
600
+ cj["default"] = true
601
+ } else {
602
+ cj["list"] = exprs(cc.List)
603
+ }
604
+ body := []J{}
605
+ for _, x := range cc.Body {
606
+ body = append(body, stmt(x))
607
+ }
608
+ cj["b"] = body
609
+ cases = append(cases, cj)
610
+ }
611
+ j["cases"] = cases
612
+ case *ast.TypeSwitchStmt:
613
+ j["s"] = "typeswitch"
614
+ case *ast.ReturnStmt:
615
+ j["s"], j["r"] = "return", exprs(s.Results)
616
+ case *ast.ForStmt:
617
+ j["s"] = "for"
618
+ case *ast.RangeStmt:
619
+ j["s"] = "range"
620
+ j["x"] = expr(s.X)
621
+ case *ast.DeclStmt:
622
+ j["s"] = "decl"
623
+ specs := []J{}
624
+ if g, ok := s.Decl.(*ast.GenDecl); ok {
625
+ for _, sp := range g.Specs {
626
+ if vs, ok := sp.(*ast.ValueSpec); ok {
627
+ names := []J{}
628
+ for _, n := range vs.Names {
629
+ o := info.Defs[n]
630
+ if o == nil {
631
+ continue
632
+ }
633
+ nj := J{"name": n.Name, "id": objID(o), "t": tid(o.Type())}
634
+ if c, ok := o.(*types.Const); ok {
635
+ nj["c"] = cval(c.Val())
636
+ }
637
+ names = append(names, nj)
638
+ }
639
+ specs = append(specs, J{"names": names, "v": exprs(vs.Values), "const": g.Tok == token.CONST})
640
+ } else {
641
+ specs = append(specs, J{"type": true})
642
+ }
643
+ }
644
+ }
645
+ j["specs"] = specs
646
+ case *ast.DeferStmt:
647
+ j["s"], j["x"] = "defer", expr(s.Call)
648
+ case *ast.GoStmt:
649
+ j["s"] = "go"
650
+ case *ast.BranchStmt:
651
+ j["s"], j["tok"] = "branch", s.Tok.String()
652
+ if s.Label != nil {
653
+ j["label"] = s.Label.Name
654
+ }
655
+ case *ast.LabeledStmt:
656
+ j["s"], j["label"], j["st"] = "labeled", s.Label.Name, stmt(s.Stmt)
657
+ case *ast.EmptyStmt:
658
+ j["s"] = "empty"
659
+ case *ast.SendStmt:
660
+ j["s"] = "send"
661
+ case *ast.SelectStmt:
662
+ j["s"] = "select"
663
+ default:
664
+ j["s"] = fmt.Sprintf("other:%T", s)
665
+ }
666
+ return j
667
+ }
668
+
669
+ // --- expressions ----------------------------------------------------------------------------------------------------
670
+ func exprs(xs []ast.Expr) []J {
671
+ out := []J{}
672
+ for _, x := range xs {
673
+ out = append(out, expr(x))
674
+ }
675
+ return out
676
+ }
677
+ func expr(x ast.Expr) J {
678
+ for {
679
+ p, ok := x.(*ast.ParenExpr)
680
+ if !ok {
681
+ break
682
+ }
683
+ x = p.X
684
+ }
685
+ tv := info.Types[x]
686
+ j := J{"p": pos(x.Pos()), "t": tid(tv.Type), "text": short(x)}
687
+ if tv.Value != nil {
688
+ j["c"] = cval(tv.Value)
689
+ }
690
+ switch x := x.(type) {
691
+ case *ast.Ident:
692
+ j["e"], j["n"] = "id", x.Name
693
+ o := info.Uses[x]
694
+ if o == nil {
695
+ o = info.Defs[x]
696
+ }
697
+ j["o"], j["id"] = objKind(o), objID(o)
698
+ case *ast.BasicLit:
699
+ j["e"] = "lit"
700
+ case *ast.SelectorExpr:
701
+ j["e"], j["n"], j["x"] = "sel", x.Sel.Name, nil
702
+ if sel, ok := info.Selections[x]; ok {
703
+ j["x"] = expr(x.X)
704
+ switch sel.Kind() {
705
+ case types.FieldVal:
706
+ j["k"] = "field"
707
+ case types.MethodVal:
708
+ j["k"] = "method"
709
+ fn := sel.Obj().(*types.Func)
710
+ sig := fn.Type().(*types.Signature)
711
+ _, ptr := sig.Recv().Type().(*types.Pointer)
712
+ j["mptr"] = ptr
713
+ rt := sig.Recv().Type()
714
+ if p, ok := rt.(*types.Pointer); ok {
715
+ rt = p.Elem()
716
+ }
717
+ if n, ok := rt.(*types.Named); ok {
718
+ j["mtype"] = n.Obj().Name()
719
+ if n.Obj().Pkg() != nil {
720
+ j["mpkg"] = n.Obj().Pkg().Path()
721
+ }
722
+ }
723
+ case types.MethodExpr:
724
+ j["k"] = "methodexpr"
725
+ }
726
+ idx := sel.Index()
727
+ j["path"] = idx
728
+ j["indirect"] = sel.Indirect()
729
+ } else {
730
+ // A qualified name: pkg.Name.
731
+ o := info.Uses[x.Sel]
732
+ j["k"] = "qual"
733
+ if o != nil && o.Pkg() != nil {
734
+ j["pkg"] = o.Pkg().Path()
735
+ } else if id, ok := x.X.(*ast.Ident); ok {
736
+ if pn, ok := info.Uses[id].(*types.PkgName); ok {
737
+ j["pkg"] = pn.Imported().Path()
738
+ }
739
+ }
740
+ j["o"] = objKind(o)
741
+ }
742
+ case *ast.CallExpr:
743
+ j["e"], j["f"], j["a"] = "call", expr(x.Fun), exprs(x.Args)
744
+ // (its end too: a check stubs an answered call by rewriting it from its position to its end)
745
+ if q := fset.Position(x.End()); q.IsValid() {
746
+ j["end"] = fmt.Sprintf("%d:%d", q.Line, q.Column)
747
+ }
748
+ if x.Ellipsis.IsValid() {
749
+ j["ell"] = true
750
+ }
751
+ if ftv, ok := info.Types[x.Fun]; ok && ftv.IsType() {
752
+ j["conv"] = true
753
+ }
754
+ if ftv, ok := info.Types[x.Fun]; ok && ftv.IsBuiltin() {
755
+ id := x.Fun
756
+ for {
757
+ if p, ok := id.(*ast.ParenExpr); ok {
758
+ id = p.X
759
+ continue
760
+ }
761
+ break
762
+ }
763
+ if i, ok := id.(*ast.Ident); ok {
764
+ j["builtin"] = i.Name
765
+ }
766
+ }
767
+ case *ast.BinaryExpr:
768
+ j["e"], j["op"], j["x"], j["y"] = "bin", x.Op.String(), expr(x.X), expr(x.Y)
769
+ case *ast.UnaryExpr:
770
+ j["e"], j["op"], j["x"] = "un", x.Op.String(), expr(x.X)
771
+ case *ast.StarExpr:
772
+ j["e"], j["x"] = "star", expr(x.X)
773
+ case *ast.CompositeLit:
774
+ j["e"] = "comp"
775
+ elts := []J{}
776
+ for _, el := range x.Elts {
777
+ if kv, ok := el.(*ast.KeyValueExpr); ok {
778
+ if id, ok := kv.Key.(*ast.Ident); ok {
779
+ if _, isField := info.Uses[id].(*types.Var); isField {
780
+ if _, st := tv.Type.Underlying().(*types.Struct); st {
781
+ elts = append(elts, J{"field": id.Name, "v": expr(kv.Value)})
782
+ continue
783
+ }
784
+ }
785
+ }
786
+ elts = append(elts, J{"k": expr(kv.Key), "v": expr(kv.Value)})
787
+ } else {
788
+ elts = append(elts, J{"v": expr(el)})
789
+ }
790
+ }
791
+ j["elts"] = elts
792
+ case *ast.IndexExpr:
793
+ j["e"], j["x"], j["i"] = "index", expr(x.X), expr(x.Index)
794
+ if xt, ok := info.Types[x.X]; ok {
795
+ if _, isSig := xt.Type.(*types.Signature); isSig {
796
+ j["e"] = "inst"
797
+ }
798
+ }
799
+ case *ast.IndexListExpr:
800
+ j["e"] = "inst"
801
+ j["x"] = expr(x.X)
802
+ case *ast.SliceExpr:
803
+ j["e"], j["x"] = "slice", expr(x.X)
804
+ if x.Low != nil {
805
+ j["lo"] = expr(x.Low)
806
+ }
807
+ if x.High != nil {
808
+ j["hi"] = expr(x.High)
809
+ }
810
+ if x.Slice3 {
811
+ j["three"] = true
812
+ }
813
+ case *ast.FuncLit:
814
+ j["e"] = "funclit"
815
+ case *ast.TypeAssertExpr:
816
+ j["e"] = "assert"
817
+ case *ast.ArrayType, *ast.MapType, *ast.StructType, *ast.InterfaceType, *ast.FuncType, *ast.ChanType, *ast.Ellipsis:
818
+ j["e"] = "type"
819
+ default:
820
+ j["e"] = fmt.Sprintf("other:%T", x)
821
+ }
822
+ return j
823
+ }
824
+ func objKind(o types.Object) string {
825
+ switch o := o.(type) {
826
+ case *types.Var:
827
+ if o.IsField() {
828
+ return "field"
829
+ }
830
+ return "var"
831
+ case *types.Const:
832
+ return "const"
833
+ case *types.Func:
834
+ return "func"
835
+ case *types.TypeName:
836
+ return "type"
837
+ case *types.Nil:
838
+ return "nil"
839
+ case *types.Builtin:
840
+ return "builtin"
841
+ case *types.PkgName:
842
+ return "pkgname"
843
+ }
844
+ return "none"
845
+ }
846
+
847
+ // The expression's text, short (for reasons).
848
+ func short(x ast.Expr) string {
849
+ var b strings.Builder
850
+ var walk func(ast.Expr)
851
+ walk = func(x ast.Expr) {
852
+ switch x := x.(type) {
853
+ case *ast.Ident:
854
+ b.WriteString(x.Name)
855
+ case *ast.SelectorExpr:
856
+ walk(x.X)
857
+ b.WriteString("." + x.Sel.Name)
858
+ case *ast.CallExpr:
859
+ walk(x.Fun)
860
+ b.WriteString("(")
861
+ for i, a := range x.Args {
862
+ if i > 0 {
863
+ b.WriteString(", ")
864
+ }
865
+ walk(a)
866
+ }
867
+ b.WriteString(")")
868
+ case *ast.BasicLit:
869
+ b.WriteString(x.Value)
870
+ case *ast.BinaryExpr:
871
+ walk(x.X)
872
+ b.WriteString(" " + x.Op.String() + " ")
873
+ walk(x.Y)
874
+ case *ast.UnaryExpr:
875
+ b.WriteString(x.Op.String())
876
+ walk(x.X)
877
+ case *ast.StarExpr:
878
+ b.WriteString("*")
879
+ walk(x.X)
880
+ case *ast.ParenExpr:
881
+ b.WriteString("(")
882
+ walk(x.X)
883
+ b.WriteString(")")
884
+ case *ast.IndexExpr:
885
+ walk(x.X)
886
+ b.WriteString("[")
887
+ walk(x.Index)
888
+ b.WriteString("]")
889
+ case *ast.CompositeLit:
890
+ b.WriteString("{...}")
891
+ default:
892
+ b.WriteString("…")
893
+ }
894
+ }
895
+ walk(x)
896
+ s := b.String()
897
+ if len(s) > 60 {
898
+ s = s[:60]
899
+ }
900
+ return s
901
+ }