forked from clipperhouse/gen
/
package.go
360 lines (300 loc) · 8.65 KB
/
package.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
package main
import (
"fmt"
"go/ast"
"go/build"
"go/doc"
"go/parser"
"go/token"
"regexp"
"strings"
_ "code.google.com/p/go.tools/go/gcimporter"
"code.google.com/p/go.tools/go/types"
)
type Package struct {
Name string
Types []*Type
}
type GenSpec struct {
Pointer, Name string // Name is included mainly for informative error messages
Methods, Projections, Containers *GenTag
}
type GenTag struct {
Items []string
Negated bool
}
// Returns one gen Package per Go package found in current directory
func getPackages() (result []*Package) {
fset := token.NewFileSet()
rootDir := "./"
astPackages, err := parser.ParseDir(fset, rootDir, nil, parser.ParseComments)
if err != nil {
errs = append(errs, err)
}
for name, astPackage := range astPackages {
pkg := &Package{Name: name}
typesPkg, err := types.Check(name, fset, getAstFiles(astPackage, rootDir))
if err != nil {
errs = append(errs, err)
}
// fall back to Universe scope if types.Check fails; "best-effort" to handle primitives, at least
scope := types.Universe
if typesPkg != nil {
scope = typesPkg.Scope()
}
docPkg := doc.New(astPackage, name, doc.AllDecls)
for _, docType := range docPkg.Types {
// look for deprecated struct tags, used for 'custom methods' in older version of gen
if t, _, err := types.Eval(docType.Name, typesPkg, scope); err == nil {
checkDeprecatedTags(t)
}
// identify marked-up types
spec, found := getGenSpec(docType.Doc, docType.Name)
if !found {
continue
}
typ := &Type{
Package: pkg,
Pointer: spec.Pointer,
Name: docType.Name,
}
standardMethods, projectionMethods, err := determineMethods(spec)
if err != nil {
errs = append(errs, err)
}
// assemble standard methods with type verification
t, _, err := types.Eval(typ.LocalName(), typesPkg, scope)
known := err == nil
if !known {
addError(fmt.Sprintf("failed to evaluate type %s (%s)", typ.Name, err))
}
if known {
numeric := isNumeric(t)
comparable := isComparable(t)
ordered := isOrdered(t)
for _, s := range standardMethods {
st, ok := standardTemplates[s]
if !ok {
addError(fmt.Sprintf("unknown standard method %s", s))
}
valid := (!st.RequiresNumeric || numeric) && (!st.RequiresComparable || comparable) && (!st.RequiresOrdered || ordered)
if valid {
typ.StandardMethods = append(typ.StandardMethods, s)
}
}
}
// assemble projections with type verification
if spec.Projections != nil {
if spec.Projections.Negated {
addError(fmt.Sprintf("negation of projected types (see projection tag on %s) is unsupported", docType.Name))
}
for _, s := range spec.Projections.Items {
numeric := false
comparable := true // sensible default?
ordered := false
t, _, err := types.Eval(s, typesPkg, scope)
known := err == nil
if !known {
addError(fmt.Sprintf("unable to identify type %s, projected on %s (%s)", s, docType.Name, err))
} else {
numeric = isNumeric(t)
comparable = isComparable(t)
ordered = isOrdered(t)
}
for _, m := range projectionMethods {
pt, ok := projectionTemplates[m]
if !ok {
addError(fmt.Sprintf("unknown projection method %v", m))
continue
}
valid := (!pt.RequiresNumeric || numeric) && (!pt.RequiresComparable || comparable) && (!pt.RequiresOrdered || ordered)
if valid {
typ.AddProjection(m, s)
}
}
}
}
if spec.Containers != nil {
if spec.Containers.Negated {
addError(fmt.Sprintf("negation of containers (see containers tag on %s) is unsupported", docType.Name))
}
typ.Containers = spec.Containers.Items
}
determineImports(typ)
pkg.Types = append(pkg.Types, typ)
}
// only add it to the results if there is something there
if len(pkg.Types) > 0 {
result = append(result, pkg)
}
}
return
}
// getGenSpec identifies gen-marked types and parses tags
func getGenSpec(doc, name string) (result *GenSpec, found bool) {
lines := strings.Split(doc, "\n")
for _, line := range lines {
if line = strings.TrimLeft(line, "/ "); strings.HasPrefix(line, "+gen") {
// parse out tags & pointer
spaces := regexp.MustCompile(" +")
parts := spaces.Split(line, -1)
var pointer string
var subsettedMethods, projectedTypes, containers *GenTag
for _, s := range parts {
if s == "*" {
pointer = s
}
if x, found, negated := parseTag("methods", s); found {
subsettedMethods = &GenTag{x, negated}
}
if x, found, negated := parseTag("projections", s); found {
projectedTypes = &GenTag{x, negated}
}
if x, found, negated := parseTag("containers", s); found {
containers = &GenTag{x, negated}
}
}
found = true
result = &GenSpec{pointer, name, subsettedMethods, projectedTypes, containers}
return
}
}
return
}
func determineMethods(spec *GenSpec) (standardMethods, projectionMethods []string, err error) {
if spec.Methods == nil || spec.Methods.Negated { // default to all
standardMethods = standardTemplates.GetAllKeys()
if spec.Projections != nil {
projectionMethods = projectionTemplates.GetAllKeys()
}
}
if spec.Methods != nil {
// categorize subsetted methods as standard or projection
std := make([]string, 0)
prj := make([]string, 0)
for _, m := range spec.Methods.Items {
isStd := standardTemplates.Contains(m)
if isStd {
std = append(std, m)
}
// only consider projection methods in presence of projected types
isPrj := spec.Projections != nil && projectionTemplates.Contains(m)
if isPrj {
prj = append(prj, m)
}
if !isStd && !isPrj {
err = fmt.Errorf("method %s is unknown on type %s", m, spec.Name)
}
}
if spec.Methods.Negated {
standardMethods = remove(standardMethods, std)
projectionMethods = remove(projectionMethods, prj)
} else {
standardMethods = std
projectionMethods = prj
}
if spec.Projections != nil && len(projectionMethods) == 0 {
err = fmt.Errorf("you've included projection types without specifying projection methods on type %s", spec.Name)
}
if len(projectionMethods) > 0 && spec.Projections == nil {
err = fmt.Errorf("you've included projection methods without specifying projection types on type %s", spec.Name)
}
}
return
}
func getAstFiles(p *ast.Package, rootDir string) (result []*ast.File) {
// pull map of *ast.File into a slice
// and skip files who's out of compile scope (Conditional compile, for example)
for name, f := range p.Files {
if ok, err := build.Default.MatchFile(rootDir, name); err != nil {
addError(fmt.Sprintf("fail to match file to compile scope (%s)", err))
} else if ok {
result = append(result, f)
}
}
return
}
func parseTag(name, s string) (result []string, found bool, negated bool) {
pattern := fmt.Sprintf(`%s:"(.*)"`, name)
r := regexp.MustCompile(pattern)
if matches := r.FindStringSubmatch(s); matches != nil && len(matches) > 1 {
found = true
match := matches[1]
if len(match) > 0 {
index := 0
if strings.HasPrefix(match, "-") {
negated = true
index = 1
}
result = strings.Split(match[index:], ",")
}
}
return
}
func determineImports(t *Type) {
imports := make(map[string]bool)
methodRequiresErrors := map[string]bool{
"First": true,
"Single": true,
"Max": true,
"Min": true,
"MaxBy": true,
"MinBy": true,
"Average": true,
}
for _, m := range t.StandardMethods {
if methodRequiresErrors[m] {
imports["errors"] = true
}
}
for _, f := range t.Projections {
if methodRequiresErrors[f.Method] {
imports["errors"] = true
}
}
methodRequiresSort := map[string]bool{
"Sort": true,
}
for _, m := range t.StandardMethods {
if methodRequiresSort[m] {
imports["sort"] = true
}
}
for _, f := range t.Projections {
if methodRequiresSort[f.Method] {
imports["sort"] = true
}
}
for s := range imports {
t.Imports = append(t.Imports, s)
}
}
func (t *Type) requiresSortSupport() bool {
for _, m := range t.StandardMethods {
if strings.HasPrefix(m, "SortBy") {
return true
}
}
return false
}
func (t *Type) requiresSortInterface() bool {
reg := regexp.MustCompile(`^Sort(Desc)?$`)
for _, m := range t.StandardMethods {
if reg.MatchString(m) {
return true
}
}
return false
}
func checkDeprecatedTags(t types.Type) {
// give informative errors for use of deprecated custom methods
switch x := t.Underlying().(type) {
case *types.Struct:
for i := 0; i < x.NumFields(); i++ {
_, found, _ := parseTag("gen", x.Tag(i))
if found {
addError(fmt.Sprintf(`custom methods (%s on %s) have been deprecated, see %s`, x.Tag(i), x.Field(i).Name(), deprecationUrl))
}
}
}
}