/
gen.go
253 lines (220 loc) · 5.84 KB
/
gen.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
package main
import (
_ "embed"
"fmt"
"go/ast"
"go/types"
"io"
"sort"
"strings"
"text/template"
"go.starlark.net/syntax"
"golang.org/x/tools/go/packages"
)
func getDocstring(def *syntax.DefStmt) (string, bool) {
body := def.Body
if len(body) == 0 {
return "", false
}
expr, ok := body[0].(*syntax.ExprStmt)
if !ok {
return "", false
}
lit, ok := expr.X.(*syntax.Literal)
if !ok {
return "", false
}
if lit.Token != syntax.STRING {
return "", false
}
return lit.Value.(string), true
}
func getSigil(decl *ast.Field) string {
if decl.Doc != nil {
for _, comment := range decl.Doc.List {
if strings.HasPrefix(comment.Text, "//starlark:") {
return comment.Text[len("//starlark:"):]
}
}
}
return ""
}
func typeStringImpl(w io.Writer, imports importSet, pkg *packages.Package, x ast.Expr) {
if x == nil {
return
}
switch x := x.(type) {
case *ast.Ident:
fmt.Fprint(w, x.Name)
case *ast.SelectorExpr:
if t, ok := pkg.TypesInfo.Types[x].Type.(*types.Named); ok && imports != nil {
pkg := t.Obj().Pkg()
imports[pkg.Path()] = packageImport{
Name: pkg.Name(),
Path: pkg.Path(),
}
}
typeStringImpl(w, imports, pkg, x.X)
fmt.Fprint(w, "."+x.Sel.Name)
case *ast.ArrayType:
fmt.Fprint(w, "[")
typeStringImpl(w, imports, pkg, x.Len)
fmt.Fprint(w, "]")
typeStringImpl(w, imports, pkg, x.Elt)
case *ast.MapType:
fmt.Fprint(w, "map[")
typeStringImpl(w, imports, pkg, x.Key)
fmt.Fprintf(w, "]")
typeStringImpl(w, imports, pkg, x.Value)
case *ast.StarExpr:
fmt.Fprint(w, "*")
typeStringImpl(w, imports, pkg, x.X)
default:
panic(fmt.Errorf("parameter types must be identifiers, selectors, arrays, slices, or pointers"))
}
}
func typeString(imports importSet, pkg *packages.Package, x ast.Expr) (type_ string, err error) {
defer func() {
if x := recover(); x != nil {
if e, ok := x.(error); ok {
err = e
return
}
panic(x)
}
}()
var buf strings.Builder
typeStringImpl(&buf, imports, pkg, x)
return buf.String(), nil
}
type packageImport struct {
Name string
Path string
}
type importSet map[string]packageImport
type functionReceiver struct {
Name string
Type string
}
type functionParam struct {
Name string
Def string
Type string
}
type functionData struct {
Name string
FactoryName string
FunctionName string
Def string
Docstring string
Receiver *functionReceiver
Params []functionParam
}
func genFunctionWrapper(imports importSet, pkg *packages.Package, f *function) (*functionData, error) {
docstring, _ := getDocstring(f.def)
data := functionData{
Name: f.decl.Name.Name,
FactoryName: f.factoryName,
FunctionName: f.functionName,
Def: f.def.Name.Name,
Docstring: docstring,
}
if f.decl.Recv != nil && len(f.decl.Recv.List) != 0 {
r := f.decl.Recv.List[0]
if len(r.Names) != 1 {
return nil, fmt.Errorf("function %v must have a named receiver", data.Name)
}
name := r.Names[0].Name
type_, err := typeString(imports, pkg, r.Type)
if err != nil {
return nil, err
}
data.Receiver = &functionReceiver{
Name: name,
Type: type_,
}
}
paramList := f.decl.Type.Params.List
if len(paramList) < 2 {
return nil, fmt.Errorf("function %v must have a signature of the form func(*starlark.Thread, *starlark.Builtin, ...)", data.Name)
}
for _, p := range paramList[2:] {
if len(p.Names) == 0 {
return nil, fmt.Errorf("all parameters to function %v must be named", data.Name)
}
type_, err := typeString(imports, pkg, p.Type)
if err != nil {
return nil, err
}
for _, id := range p.Names {
data.Params = append(data.Params, functionParam{
Name: id.Name,
Type: type_,
})
}
}
if len(f.def.Params) != len(data.Params) && f.functionName != f.decl.Name.Name {
return nil, fmt.Errorf("definition and declaration of %v have different parameter counts", data.Name)
}
for i, p := range f.def.Params {
name, sigil := "", ""
switch p := p.(type) {
case *syntax.Ident:
name = p.Name
case *syntax.BinaryExpr:
name = p.X.(*syntax.Ident).Name
value, ok := p.Y.(*syntax.Ident)
if !ok || value.Name != "None" {
return nil, fmt.Errorf("default value for parameter %v in function %v must be None", name, data.Name)
}
sigil = "??"
}
data.Params[i].Def = name + sigil
}
return &data, nil
}
func genFunctionWrappers(w io.Writer, pkg *packages.Package, fns []*function) error {
var data struct {
Package string
Imports []packageImport
Functions []*functionData
}
imports := importSet{}
imports["go.starlark.net/starlark"] = packageImport{Path: "go.starlark.net/starlark"}
for _, fn := range fns {
fnData, err := genFunctionWrapper(imports, pkg, fn)
if err != nil {
return err
}
data.Functions = append(data.Functions, fnData)
}
data.Imports = make([]packageImport, 0, len(imports))
for _, imp := range imports {
data.Imports = append(data.Imports, imp)
}
sort.Slice(data.Imports, func(i, j int) bool {
return data.Imports[i].Path < data.Imports[j].Path
})
data.Package = pkg.Types.Name()
return functionWrappersTemplate.Execute(w, data)
}
func genModuleDocs(w io.Writer, m *object) error {
return moduleDocsTemplate.Execute(w, m)
}
//go:embed function_wrappers.tmpl
var functionWrappersTemplateText string
//go:embed object_docs.tmpl
var objectDocsTemplateText string
//go:embed module_docs.tmpl
var moduleDocsTemplateText string
var functionWrappersTemplate *template.Template
var moduleDocsTemplate *template.Template
func init() {
functionWrappersTemplate = template.Must(template.New("FunctionWrappers").Funcs(template.FuncMap{
"sanitize": func(s string) string {
return strings.ReplaceAll(s, "`", "`+\"`\"+`")
},
}).Parse(functionWrappersTemplateText))
moduleDocsTemplate = template.Must(template.New("ModuleDocs").Parse(moduleDocsTemplateText))
template.Must(moduleDocsTemplate.New("Object").Parse(objectDocsTemplateText))
}