Repository navigation
Expand file tree
/
Copy pathapi.go
More file actions
460 lines (446 loc) · 12.3 KB
/
Copy pathapi.go
File metadata and controls
460 lines (446 loc) · 12.3 KB
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package check
import (
"sort"
"strconv"
"strings"
"github.com/GiGurra/bork/internal/diag"
"github.com/GiGurra/bork/internal/doccomment"
"github.com/GiGurra/bork/internal/syntax"
)
// PackageAPI is an owned view of the declarations an importer can use.
type PackageAPI struct {
Path, Documentation string
Unsafe bool
Declarations []APIDeclaration
}
type APIDeclaration struct {
Kind, Name, Receiver, Signature, Documentation string
Position diag.Pos
}
func API(info *Info, files []*syntax.File, path string) *PackageAPI {
var pkg *Package
for _, p := range info.Packages {
if p.Path == path {
pkg = p
break
}
}
if pkg == nil {
return nil
}
return packageAPI(pkg, files, path, false)
}
func packageAPI(pkg *Package, files []*syntax.File, path string, builtin bool) *PackageAPI {
visible := Exported
if builtin {
visible = PreludeVisible
}
out := &PackageAPI{Path: path}
var sources []*syntax.File
for _, f := range files {
if builtin && f.Prelude || !builtin && !f.Prelude && f.Package == path {
sources = append(sources, f)
}
}
sort.Slice(sources, func(i, j int) bool { return sources[i].Path < sources[j].Path })
var summaries []string
for _, f := range sources {
if text := doccomment.Package(f); text != "" {
summaries = append(summaries, text)
}
for _, fn := range f.Funcs {
out.Unsafe = out.Unsafe || fn.IsGo()
}
}
out.Documentation = strings.Join(summaries, "\n\n")
add := func(kind, name, receiver, signature string, pos diag.Pos) {
doc := apiComment(sources, pos)
out.Declarations = append(out.Declarations, APIDeclaration{kind, name, receiver, signature, doc, pos})
}
for name, e := range pkg.types {
if visible(name) {
signature := apiType(e.decl, sources)
if builtin && e.decl.Private {
signature = "type " + name + apiParams(e.decl.TypeParams) + " = private { ... }"
}
add("type", name, "", signature, e.decl.Pos)
}
}
for name, fn := range pkg.Funcs {
if fn.Decl == nil || fn.Of != nil || fn.Synthetic || fn.Class != nil || !visible(name) {
continue
}
kind := "function"
if fn.Decl.IsPred {
kind = "predicate"
}
if fn.Decl.Constructor != nil {
kind = "constructor"
}
add(kind, name, "", apiFunction(fn), fn.Decl.Pos)
}
for name, helper := range pkg.deriveHelpers {
if visible(name) {
add("derive helper", name, "", DeriveHelperSignature(helper), helper.Pos)
}
}
for _, methods := range pkg.methods {
for name, fn := range methods {
if visible(name) {
add("method", name, writtenTypeText(fn.Decl.Params[0].Type), apiFunction(fn), fn.Decl.Pos)
}
}
}
for name, class := range pkg.classes {
if !visible(name) {
continue
}
var signatures []string
for _, fn := range class.Methods {
signature := apiFunction(fn)
if doc := apiComment(sources, fn.Decl.Pos); doc != "" {
signature = "// " + strings.ReplaceAll(doc, "\n", "\n// ") + "\n" + signature
}
signatures = append(signatures, " "+strings.ReplaceAll(signature, "\n", "\n "))
}
add("class", name, "", "class "+name+apiParams(class.Decl.TypeParams)+" {\n"+strings.Join(signatures, "\n")+"\n}", class.Decl.Pos)
}
for _, instance := range pkg.instances {
if visible(instance.Name) && instance.Decl != nil {
sig := "instance " + instance.Name + apiParams(instance.Decl.TypeParams) + ": " + qualify(instance.Class.Name, instance.Class.Pkg, pkg) + "[" + writtenTypeText(instance.Decl.Type) + "]"
if instance.Derived != "" {
sig = "instance " + instance.Name + apiParams(instance.Decl.TypeParams) + ": " + qualify(instance.Class.Name, instance.Class.Pkg, pkg) + "[" + TypeText(instance.Type, pkg) + "]"
if len(instance.Constraints) > 0 {
sig = strings.TrimSuffix(sig, "]") + " where " + constraintsText(instance.Constraints, pkg) + "]"
}
}
add("instance", instance.Name, "", sig, instance.Decl.Pos)
}
}
for name, bundle := range pkg.bundles {
if visible(name) {
var names []string
for _, item := range bundle.decl.Items {
names = append(names, item.Name)
}
add("instances", name, "", "instances "+name+" { "+strings.Join(names, ", ")+" }", bundle.decl.Pos)
}
}
for name, a := range pkg.ambients {
if visible(name) {
sig := "ambient " + name + ": " + writtenTypeText(a.Decl.Type)
if a.Logged {
sig = "logged " + sig
}
if a.Header != "" {
sig = "propagated(" + strconv.Quote(a.Header) + ") " + sig
}
add("ambient", name, "", sig, a.Decl.Pos)
}
}
for name, b := range pkg.bindings {
if visible(name) {
typ := TypeText(b.Type, pkg)
if b.Decl.Type != nil {
typ = writtenTypeText(b.Decl.Type)
}
sig := name + ": " + typ
if b.Decl.Lazy {
sig = "lazy " + sig
}
add("value", name, "", sig, b.Decl.Pos)
}
}
sort.Slice(out.Declarations, func(i, j int) bool {
a, b := out.Declarations[i], out.Declarations[j]
if a.Kind != b.Kind {
return a.Kind < b.Kind
}
if a.Receiver != b.Receiver {
return a.Receiver < b.Receiver
}
return a.Name < b.Name
})
return out
}
func apiComment(sources []*syntax.File, pos diag.Pos) string {
for _, source := range sources {
if source.Path == pos.File {
return doccomment.At(source, pos)
}
}
return ""
}
func apiParams(params []*syntax.TypeParam) string {
if len(params) == 0 {
return ""
}
var parts []string
for _, p := range params {
text := p.Name
if len(p.Bounds) > 0 {
text += ": " + strings.Join(p.Bounds, " + ")
}
parts = append(parts, text)
}
return "[" + strings.Join(parts, ", ") + "]"
}
// DeriveHelperSignature preserves source type projections and symbolic parameters
// without exposing any generated runtime specialization.
func DeriveHelperSignature(fd *syntax.FuncDecl) string {
var params []string
for _, param := range fd.Params {
params = append(params, param.Name+": "+writtenTypeText(param.Type))
}
text := "derive fn " + fd.Name + apiParams(fd.TypeParams) + "(" + strings.Join(params, ", ") + ")"
if fd.Requires != nil {
text += " where " + deriveSignatureExpr(fd.Requires)
}
if fd.Uses != nil {
var effects []string
for _, effect := range fd.Uses.Effects {
effects = append(effects, effect.Name)
}
if len(effects) == 0 {
effects = append(effects, "nothing")
}
text += " uses " + strings.Join(effects, " + ")
}
if fd.Needs != nil {
var needs []string
for _, need := range fd.Needs.Items {
name := need.Name
if need.Optional {
name += "?"
}
needs = append(needs, name)
}
text += " needs " + strings.Join(needs, " + ")
}
result := "Ok"
if fd.Result != nil {
result = writtenTypeText(fd.Result)
}
return text + ": " + result
}
func deriveSignatureExpr(expr syntax.Expr) string {
switch expr := expr.(type) {
case *syntax.Call:
var types, args []string
for _, typ := range expr.TypeArgs {
types = append(types, writtenTypeText(typ))
}
for i, arg := range expr.Args {
text := deriveSignatureExpr(arg)
if i < len(expr.Arguments) && expr.Arguments[i].Name != "" {
text = expr.Arguments[i].Name + ": " + text
}
args = append(args, text)
}
head := deriveSignatureExpr(expr.Fun)
if len(types) > 0 {
head += "[" + strings.Join(types, ", ") + "]"
}
return head + "(" + strings.Join(args, ", ") + ")"
case *syntax.Binary:
return "(" + deriveSignatureExpr(expr.X) + " " + strings.Trim(expr.Op.String(), "'") + " " + deriveSignatureExpr(expr.Y) + ")"
case *syntax.Unary:
return strings.Trim(expr.Op.String(), "'") + deriveSignatureExpr(expr.X)
}
if text := defaultText(expr); text != "" {
return text
}
return "<expression>"
}
func apiFunction(fn *Func) string {
fd := fn.Decl
keyword := "fn"
if fd.IsPred {
keyword = "pred"
}
text := keyword + " "
param := func(p *syntax.Param) string {
value := p.Name + ": " + writtenTypeText(p.Type)
if p.In != "" {
value += " in " + p.In
}
if p.Default != nil {
value += " = " + apiDefault(p.Default)
}
return value
}
start := 0
if fd.IsMethod {
text += "(" + param(fd.Params[0]) + ") "
start = 1
}
var params []string
for _, p := range fd.Params[start:] {
params = append(params, param(p))
}
text += fd.Name + apiParams(fd.TypeParams) + "(" + strings.Join(params, ", ") + ")"
if fn.Requires != nil {
text += " where " + requirementText(fn.Requires, fn.Pkg)
}
if fd.Uses != nil || fn.Effects != 0 {
text += " " + usesText(fd, fn.Effects)
}
callable := DescribeCallable(fn, fn.Params, fn.Pkg, false)
if len(callable.Needs) > 0 {
text += " needs " + strings.Join(callable.Needs, " + ")
}
result := writtenTypeText(fd.Result)
if fd.Result == nil {
result = TypeText(fn.Result, fn.Pkg)
}
if !fd.IsPred {
text += ": " + result
}
if fd.IsGo() {
text += " unsafe go"
}
if fd.Constructor != nil && constructorInvariant(fn) {
text += "\n// " + strings.Join(callable.Requires, "; ")
}
return text
}
// Computed defaults expose their presence, without rendering implementation code.
func apiDefault(expr syntax.Expr) string {
if text := defaultText(expr); apiDefaultSupported(expr) && text != "" {
return text
}
return "<computed>"
}
func apiDefaultSupported(expr syntax.Expr) bool {
switch x := expr.(type) {
case *syntax.IntLit, *syntax.FloatLit, *syntax.RuneLit, *syntax.StringLit, *syntax.BoolLit, *syntax.Ident, *syntax.TypeHead, *syntax.ContextName:
return true
case *syntax.Unary:
return apiDefaultSupported(x.X)
case *syntax.Selector:
return apiDefaultSupported(x.X)
case *syntax.Call:
if !apiDefaultSupported(x.Fun) {
return false
}
for _, arg := range x.Args {
if !apiDefaultSupported(arg) {
return false
}
}
return true
case *syntax.TupleLit:
for _, e := range x.Elems {
if !apiDefaultSupported(e) {
return false
}
}
return true
case *syntax.ListLit:
for _, e := range x.Elems {
if !apiDefaultSupported(e) {
return false
}
}
return true
case *syntax.MapLit:
for i, key := range x.Keys {
if !apiDefaultSupported(key) || !apiDefaultSupported(x.Values[i]) {
return false
}
}
return true
case *syntax.RecordLit:
if !apiDefaultSupported(x.Type) {
return false
}
for _, field := range x.Fields {
if !apiDefaultSupported(field.Value) {
return false
}
}
return true
}
return false
}
func apiFields(fields []*syntax.FieldDecl, sources []*syntax.File) string {
var parts []string
for _, f := range fields {
text := f.Name + ": " + writtenTypeText(f.Type)
if f.Lazy {
text = "lazy " + text
}
if f.Default != nil {
text += " = " + apiDefault(f.Default)
}
if doc := apiComment(sources, f.Pos); doc != "" {
text = "// " + strings.ReplaceAll(doc, "\n", "\n // ") + "\n " + text
}
parts = append(parts, " "+text)
}
return "{\n" + strings.Join(parts, ",\n") + "\n}"
}
func apiType(td *syntax.TypeDecl, sources []*syntax.File) string {
text := "type " + td.Name + apiParams(td.TypeParams) + " = "
if td.MetadataFamily {
text = syntax.MetadataFamilyKeyword + " " + text
}
if td.Private {
text += "private "
}
switch td.Kind {
case syntax.RecordType:
text += apiFields(td.Fields, sources)
case syntax.SealedType:
var variants []string
private := false
for _, v := range td.Variants {
if !Exported(v.Name) {
private = true
continue
}
value := v.Name
if doc := apiComment(sources, v.Pos); doc != "" {
value = "// " + strings.ReplaceAll(doc, "\n", "\n // ") + "\n " + value
}
if v.Positional {
var slots []string
for _, slot := range v.Slots {
slots = append(slots, writtenTypeText(slot))
}
value += "(" + strings.Join(slots, ", ") + ")"
} else if len(v.Fields) > 0 {
value += " " + apiFields(v.Fields, sources)
}
if len(v.Where) > 0 {
var clauses []string
for _, q := range v.Where {
clauses = append(clauses, writtenPredText(q))
}
value += " where " + strings.Join(clauses, " and ")
}
variants = append(variants, value)
}
if private {
variants = append(variants, "// additional variants are private")
}
text += "sealed {\n " + strings.Join(variants, ",\n ") + "\n}"
case syntax.AliasType:
text += writtenTypeText(td.Alias)
case syntax.ResourceType:
text += "resource"
case syntax.GoType:
text += "go " + strconv.Quote(td.GoName.Name)
}
if len(td.Where) > 0 {
var clauses []string
for _, q := range td.Where {
clauses = append(clauses, writtenPredText(q))
}
text += " where " + strings.Join(clauses, " and ")
}
if len(td.Derive) > 0 {
text += " derive (" + strings.Join(td.Derive, ", ") + ")"
}
return text
}