-
Notifications
You must be signed in to change notification settings - Fork 30
/
memoize.go
292 lines (242 loc) · 6.29 KB
/
memoize.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
package memoize
import (
"bytes"
"errors"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/printer"
"go/token"
"go/types"
"os"
"strings"
"text/template"
"github.com/Mzack9999/gcache"
"github.com/cespare/xxhash"
singleflight "github.com/projectdiscovery/utils/memoize/simpleflight"
stringsutil "github.com/projectdiscovery/utils/strings"
"golang.org/x/tools/imports"
)
type Memoizer struct {
cache gcache.Cache[uint64, interface{}]
group singleflight.Group[uint64]
}
type MemoizeOption func(m *Memoizer) error
func WithMaxSize(size int) MemoizeOption {
return func(m *Memoizer) error {
m.cache = gcache.
New[uint64, interface{}](size).
EvictedFunc(func(k uint64, _ interface{}) {
m.group.Forget(k)
}).
Build()
return nil
}
}
func New(options ...MemoizeOption) (*Memoizer, error) {
m := &Memoizer{}
for _, option := range options {
if err := option(m); err != nil {
return nil, err
}
}
return m, nil
}
func (m *Memoizer) Do(funcHash string, fn func() (interface{}, error)) (interface{}, error, bool) {
hash := xxhash.Sum64String(funcHash)
if value, err := m.cache.GetIFPresent(hash); !errors.Is(err, gcache.KeyNotFoundError) {
return value, err, true
}
value, err, _ := m.group.Do(hash, func() (interface{}, error) {
data, err := fn()
if err == nil {
_ = m.cache.Set(hash, data)
}
return data, err
})
return value, err, false
}
func File(tpl, sourceFile, packageName string) ([]byte, error) {
data, err := os.ReadFile(sourceFile)
if err != nil {
return nil, err
}
return Src(tpl, sourceFile, data, packageName)
}
func Src(tpl, sourcePath string, source []byte, packageName string) ([]byte, error) {
var (
fileData FileData
content bytes.Buffer
)
tmpl, err := template.New("package_template").Parse(tpl)
if err != nil {
return nil, err
}
fileData.PackageName = packageName
fset := token.NewFileSet()
node, err := parser.ParseFile(fset, sourcePath, source, parser.ParseComments)
if err != nil {
return nil, err
}
for _, nn := range node.Imports {
var packageImport PackageImport
if nn.Name != nil {
packageImport.Name = nn.Name.Name
}
if nn.Path != nil {
packageImport.Path = nn.Path.Value
}
fileData.Imports = append(fileData.Imports, packageImport)
}
fileData.SourcePackage = node.Name.Name
ast.Inspect(node, func(n ast.Node) bool {
switch nn := n.(type) {
case *ast.FuncDecl:
if nn.Doc == nil {
return false
}
var funcDeclaration FunctionDeclaration
funcDeclaration.IsExported = nn.Name.IsExported()
funcDeclaration.Name = nn.Name.Name
funcDeclaration.SourcePackage = fileData.SourcePackage
var funcSign strings.Builder
printer.Fprint(&funcSign, fset, nn.Type)
funcDeclaration.Signature = strings.Replace(funcSign.String(), "func", "func "+funcDeclaration.Name, 1)
for _, comment := range nn.Doc.List {
if comment.Text == "// @memo" {
if nn.Type.Params != nil {
for idx, param := range nn.Type.Params.List {
var funcParam FuncValue
funcParam.Index = idx
for _, name := range param.Names {
funcParam.Name = name.String()
}
funcParam.Type = fmt.Sprint(param.Type)
funcDeclaration.Params = append(funcDeclaration.Params, funcParam)
}
}
if nn.Type.Results != nil {
for idx, res := range nn.Type.Results.List {
var result FuncValue
result.Index = idx
for _, name := range res.Names {
result.Name = name.String()
}
result.Type = types.ExprString(res.Type)
funcDeclaration.Results = append(funcDeclaration.Results, result)
}
}
fileData.Functions = append(fileData.Functions, funcDeclaration)
}
}
return false
default:
return true
}
})
err = tmpl.Execute(&content, fileData)
if err != nil {
return nil, err
}
out, err := imports.Process(sourcePath, content.Bytes(), nil)
if err != nil {
return nil, err
}
return format.Source(out)
}
type PackageImport struct {
Name string
Path string
}
type FuncValue struct {
Index int
Name string
Type string
}
func (f FuncValue) ResultName() string {
return fmt.Sprintf("result%d", f.Index)
}
type FunctionDeclaration struct {
SourcePackage string
IsExported bool
Name string
Params []FuncValue
Results []FuncValue
Signature string
}
func (f FunctionDeclaration) HasParams() bool {
return len(f.Params) > 0
}
func (f FunctionDeclaration) SignatureWithPrefix(prefix string) string {
return strings.Replace(f.Signature, f.Name, prefix+f.Name, 1)
}
func (f FunctionDeclaration) ParamsNames() string {
var params []string
for _, param := range f.Params {
params = append(params, param.Name)
}
return strings.Join(params, ",")
}
func (f FunctionDeclaration) HasReturn() bool {
return len(f.Results) > 0
}
func (f FunctionDeclaration) WantSyncOnce() bool {
return !f.HasParams()
}
func (f FunctionDeclaration) SyncOnceVarName() string {
return fmt.Sprintf("once%s", f.Name)
}
func (f FunctionDeclaration) WantReturn() bool {
return f.HasReturn()
}
func (f FunctionDeclaration) ResultStructType() string {
return fmt.Sprintf("result%s", f.Name)
}
func (f FunctionDeclaration) ResultStructVarName() string {
return fmt.Sprintf("v%s", f.ResultStructType())
}
func (f FunctionDeclaration) ResultStructFields() string {
var results []string
for _, result := range f.Results {
results = append(results, fmt.Sprintf("%s.%s", f.ResultStructVarName(), result.ResultName()))
}
return strings.Join(results, ",")
}
func (f FunctionDeclaration) ResultFields() string {
var results []string
for _, result := range f.Results {
results = append(results, result.ResultName())
}
return strings.Join(results, ",")
}
func (f FunctionDeclaration) ResultFirstFieldType() string {
if len(f.Results) > 0 {
fieldType := f.Results[0].Type
return fieldType
}
panic("invalid signature type")
}
func (f FunctionDeclaration) ResultFirstFieldDefaultValue() string {
if len(f.Results) > 0 {
fieldType := f.Results[0].Type
if stringsutil.HasPrefixAny(fieldType, "*") {
return "nil"
}
switch fieldType {
case "bool":
return "false"
case "string":
return `""`
default:
return fieldType + "{}"
}
}
panic("invalid signature type")
}
type FileData struct {
PackageName string
SourcePackage string
Imports []PackageImport
Functions []FunctionDeclaration
}