This repository has been archived by the owner on Mar 19, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
reduce.go
353 lines (324 loc) · 7.42 KB
/
reduce.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
// Copyright (c) 2017, Daniel Martí <[email protected]>
// See LICENSE for licensing information
package main
import (
"bytes"
"context"
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/printer"
"go/token"
"go/types"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"mvdan.cc/sh/v3/interp"
"mvdan.cc/sh/v3/syntax"
)
var (
rawPrinter = printer.Config{Mode: printer.RawFormat}
fastTest = false
)
type reducer struct {
tdir string
logOut io.Writer
matchRe *regexp.Regexp
shellProg *syntax.File
fset *token.FileSet
origFset *token.FileSet
pkg *ast.Package
files []*ast.File
file *ast.File
tconf types.Config
info *types.Info
useIdents map[types.Object][]*ast.Ident
revDefs map[types.Object]*ast.Ident
parents map[ast.Node]ast.Node
dstBuf *bytes.Buffer
tmpFiles map[*ast.File]*os.File
tries int
didChange bool
deleteKeepUnderscore func()
deleteKeepUnchanged func()
tried map[string]bool
walker
}
var errNoReduction = fmt.Errorf("could not reduce program")
func reduce(dir, match string, logOut io.Writer, shellStr string) error {
r := &reducer{
tdir: dir,
logOut: logOut,
tried: make(map[string]bool, 16),
dstBuf: bytes.NewBuffer(nil),
}
var err error
if r.tdir, err = ioutil.TempDir("", "goreduce"); err != nil {
return err
}
if err := ioutil.WriteFile(
filepath.Join(r.tdir, "go.mod"),
[]byte("module tmp"), 0666,
); err != nil {
return err
}
defer os.RemoveAll(r.tdir)
if r.matchRe, err = regexp.Compile(match); err != nil {
return err
}
r.fset = token.NewFileSet()
pkgs, err := parser.ParseDir(r.fset, dir, nil, parser.ParseComments)
if err != nil {
return err
}
if len(pkgs) != 1 {
return fmt.Errorf("expected 1 package, got %d", len(pkgs))
}
for _, pkg := range pkgs {
r.pkg = pkg
}
switch {
case shellStr != "":
case r.pkg.Name == "main":
shellStr = shellStrRun
default:
shellStr = shellStrBuild
}
r.shellProg, err = syntax.NewParser().Parse(strings.NewReader(shellStr), "")
if err != nil {
return err
}
r.origFset = token.NewFileSet()
parser.ParseDir(r.origFset, dir, nil, 0)
var restoreMain func()
r.tmpFiles = make(map[*ast.File]*os.File, len(r.pkg.Files))
for fpath, file := range r.pkg.Files {
r.files = append(r.files, file)
tfname := filepath.Join(r.tdir, filepath.Base(fpath))
f, err := os.Create(tfname)
if err != nil {
return err
}
if err := rawPrinter.Fprint(f, r.fset, file); err != nil {
return err
}
r.tmpFiles[file] = f
defer f.Close()
}
r.tconf.Importer = importer.Default()
r.tconf.Error = func(err error) {
if terr, ok := err.(types.Error); ok && terr.Soft {
// don't stop type-checking on soft errors
return
}
//panic("types.Check should not error here: " + err.Error())
}
// Check that the output matches before we apply any changes
if !fastTest {
if err := r.checkRun(); err != nil {
return err
}
}
r.fillParents()
if anyChanges := r.reduceLoop(); !anyChanges {
return errNoReduction
}
if restoreMain != nil {
restoreMain()
}
for astFile := range r.tmpFiles {
astFile.Name.Name = r.pkg.Name
fname := r.fset.Position(astFile.Pos()).Filename
f, err := os.Create(fname)
if err != nil {
return err
}
if err := printer.Fprint(f, r.fset, astFile); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
}
return nil
}
func (r *reducer) logChange(node ast.Node, format string, a ...interface{}) {
if *verbose {
pos := r.origFset.Position(node.Pos())
times := "first try"
if r.tries != 1 {
times = fmt.Sprintf("%d tries", r.tries)
}
fmt.Fprintf(r.logOut, "%s:%d: %s (%s)\n",
pos.Filename, pos.Line, fmt.Sprintf(format, a...), times)
}
r.tries = 0
}
func (r *reducer) checkRun() error {
out := r.runCmd()
if out == nil {
return fmt.Errorf("expected an error to occur")
}
if !r.matchRe.Match(out) {
return fmt.Errorf("error does not match:\n%s", string(out))
}
return nil
}
func (r *reducer) okChangeNoUndo() bool {
if r.didChange {
return false
}
r.dstBuf.Reset()
if err := rawPrinter.Fprint(r.dstBuf, r.fset, r.file); err != nil {
return false
}
newSrc := r.dstBuf.String()
if r.tried[newSrc] {
return false
}
r.tries++
r.tried[newSrc] = true
f := r.tmpFiles[r.file]
if err := f.Truncate(0); err != nil {
return false
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return false
}
if _, err := f.Write(r.dstBuf.Bytes()); err != nil {
return false
}
if err := r.checkRun(); err != nil {
return false
}
// Reduction worked
r.didChange = true
return true
}
func (r *reducer) okChange() bool {
if r.okChangeNoUndo() {
r.deleteKeepUnderscore = nil
r.deleteKeepUnchanged = nil
return true
}
if r.deleteKeepUnderscore != nil {
r.deleteKeepUnderscore()
r.deleteKeepUnderscore = nil
return r.okChange()
}
if r.deleteKeepUnchanged != nil {
r.deleteKeepUnchanged()
r.deleteKeepUnchanged = nil
}
return false
}
func (r *reducer) reduceLoop() (anyChanges bool) {
r.info = &types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
for {
// Update type info after the AST changes
r.tconf.Check(r.tdir, r.fset, r.files, r.info)
r.fillObjs()
r.didChange = false
r.walk(r.pkg, r.reduceNode)
if !r.didChange {
if *verbose {
fmt.Fprintf(r.logOut, "gave up after %d final tries\n", r.tries)
}
return
}
anyChanges = true
}
}
func (r *reducer) fillObjs() {
r.revDefs = make(map[types.Object]*ast.Ident, len(r.info.Defs))
for id, obj := range r.info.Defs {
if obj == nil {
continue
}
r.revDefs[obj] = id
}
r.useIdents = make(map[types.Object][]*ast.Ident, len(r.info.Uses)/2)
for id, obj := range r.info.Uses {
if pkg := obj.Pkg(); pkg == nil || pkg.Name() != r.pkg.Name {
// builtin or declared outside of our pkg
continue
}
r.useIdents[obj] = append(r.useIdents[obj], id)
}
}
func (r *reducer) fillParents() {
r.parents = make(map[ast.Node]ast.Node)
stack := make([]ast.Node, 1, 32)
ast.Inspect(r.pkg, func(node ast.Node) bool {
if node == nil {
stack = stack[:len(stack)-1]
return true
}
r.parents[node] = stack[len(stack)-1]
stack = append(stack, node)
return true
})
}
func (r *reducer) runCmd() []byte {
var buf bytes.Buffer
runner, err := interp.New(interp.Dir(r.tdir), interp.StdIO(nil, &buf, &buf))
if err != nil {
panic(err)
}
runner.Run(context.TODO(), r.shellProg)
return buf.Bytes()
}
func (r *reducer) exprRef(expr ast.Expr) *ast.Expr {
parent := r.parents[expr]
v := reflect.ValueOf(parent).Elem()
for i := 0; i < v.NumField(); i++ {
fld := v.Field(i)
switch fld.Type().Kind() {
case reflect.Slice:
for i := 0; i < fld.Len(); i++ {
ifld := fld.Index(i)
if ifld.Interface() == expr {
ptr, _ := ifld.Addr().Interface().(*ast.Expr)
return ptr
}
}
case reflect.Interface:
if fld.Interface() == expr {
ptr, _ := fld.Addr().Interface().(*ast.Expr)
return ptr
}
}
}
return nil
}
func (r *reducer) stmtRef(stmt ast.Stmt) *ast.Stmt {
parent := r.parents[stmt]
v := reflect.ValueOf(parent).Elem()
for i := 0; i < v.NumField(); i++ {
fld := v.Field(i)
switch fld.Type().Kind() {
case reflect.Slice:
for i := 0; i < fld.Len(); i++ {
ifld := fld.Index(i)
if ifld.Interface() == stmt {
ptr, _ := ifld.Addr().Interface().(*ast.Stmt)
return ptr
}
}
case reflect.Interface:
if fld.Interface() == stmt {
ptr, _ := fld.Addr().Interface().(*ast.Stmt)
return ptr
}
}
}
return nil
}