forked from mdempsky/unconvert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunconvert.go
437 lines (394 loc) · 8.93 KB
/
unconvert.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
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
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Unconvert removes redundant type conversions from Go packages.
package main
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/parser"
"go/token"
"go/types"
"io/ioutil"
"log"
"os"
"reflect"
"runtime/pprof"
"sort"
"sync"
"unicode"
"golang.org/x/tools/container/intsets"
"golang.org/x/tools/go/loader"
)
// Unnecessary conversions are identified by the position
// of their left parenthesis within a source file.
func apply(file string, edits *intsets.Sparse) {
if edits.IsEmpty() {
return
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, file, nil, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
// Note: We modify edits during the walk.
v := editor{edits: edits, file: fset.File(f.Package)}
ast.Walk(&v, f)
if !edits.IsEmpty() {
log.Printf("%s: missing edits %s", file, edits)
}
// TODO(mdempsky): Write to temporary file and rename.
var buf bytes.Buffer
err = format.Node(&buf, fset, f)
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile(file, buf.Bytes(), 0)
if err != nil {
log.Fatal(err)
}
}
type editor struct {
edits *intsets.Sparse
file *token.File
}
func (e *editor) Visit(n ast.Node) ast.Visitor {
if n == nil {
return nil
}
v := reflect.ValueOf(n).Elem()
for i, n := 0, v.NumField(); i < n; i++ {
switch f := v.Field(i).Addr().Interface().(type) {
case *ast.Expr:
e.rewrite(f)
case *[]ast.Expr:
for i := range *f {
e.rewrite(&(*f)[i])
}
}
}
return e
}
func (e *editor) rewrite(f *ast.Expr) {
n, ok := (*f).(*ast.CallExpr)
if !ok {
return
}
off := e.file.Offset(n.Lparen)
if !e.edits.Has(off) {
return
}
*f = n.Args[0]
e.edits.Remove(off)
}
func print(name string, edits *intsets.Sparse) {
if edits.IsEmpty() {
return
}
buf, err := ioutil.ReadFile(name)
if err != nil {
log.Fatal(err)
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, name, buf, 0)
if err != nil {
log.Fatal(err)
}
file := fset.File(f.Package)
for _, p := range edits.AppendTo(nil) {
pos := file.Position(file.Pos(p))
if *flagOneLiners {
fmt.Printf("%s:%d:%d: useless conversion\n", pos.Filename, pos.Line,
pos.Column)
} else {
fmt.Printf("%s:%d:%d:\n", pos.Filename, pos.Line, pos.Column)
line := lineForOffset(buf, pos.Offset)
fmt.Printf("%s\n", line)
fmt.Printf("%s^\n", rub(line[:pos.Column-1]))
}
}
}
func rub(buf []byte) []byte {
// TODO(mdempsky): Handle combining characters?
// TODO(mdempsky): Handle East Asian wide characters?
var res bytes.Buffer
for _, c := range string(buf) {
if !unicode.IsSpace(c) {
c = ' '
}
res.WriteRune(c)
}
return res.Bytes()
}
func lineForOffset(buf []byte, off int) []byte {
sol := bytes.LastIndexByte(buf[:off], '\n')
if sol < 0 {
sol = 0
} else {
sol += 1
}
eol := bytes.IndexByte(buf[off:], '\n')
if eol < 0 {
eol = len(buf)
} else {
eol += off
}
return buf[sol:eol]
}
var (
flagAll = flag.Bool("all", false, "type check all GOOS and GOARCH combinations")
flagApply = flag.Bool("apply", false, "apply edits to source files")
flagCPUProfile = flag.String("cpuprofile", "", "write CPU profile to file")
flagOneLiners = flag.Bool("oneliners", false, "outputs 1 line per case")
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: unconvert [flags] [package ...]\n")
flag.PrintDefaults()
}
func main() {
flag.Usage = usage
flag.Parse()
if *flagCPUProfile != "" {
f, err := os.Create(*flagCPUProfile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
var m map[string]*intsets.Sparse
if *flagAll {
m = mergeEdits()
} else {
m = computeEdits(build.Default.GOOS, build.Default.GOARCH, build.Default.CgoEnabled)
}
if *flagApply {
var wg sync.WaitGroup
for f, e := range m {
wg.Add(1)
f, e := f, e
go func() {
defer wg.Done()
apply(f, e)
}()
}
wg.Wait()
} else {
var files []string
for f := range m {
files = append(files, f)
}
sort.Strings(files)
for _, f := range files {
print(f, m[f])
}
}
}
var plats = [...]struct {
goos, goarch string
}{
// TODO(mdempsky): buildall.bash also builds linux-386-387 and linux-arm-arm5.
{"linux", "386"},
{"linux", "amd64"},
{"linux", "arm"},
{"linux", "arm64"},
{"linux", "mips64"},
{"linux", "mips64le"},
{"linux", "ppc64"},
{"linux", "ppc64le"},
{"nacl", "386"},
{"nacl", "amd64p32"},
{"nacl", "arm"},
{"android", "386"},
{"android", "amd64"},
{"darwin", "386"},
{"darwin", "amd64"},
{"dragonfly", "amd64"},
{"freebsd", "386"},
{"freebsd", "amd64"},
{"freebsd", "arm"},
{"netbsd", "386"},
{"netbsd", "amd64"},
{"netbsd", "arm"},
{"openbsd", "386"},
{"openbsd", "amd64"},
{"openbsd", "arm"},
{"plan9", "386"},
{"plan9", "amd64"},
{"solaris", "amd64"},
{"windows", "386"},
{"windows", "amd64"},
}
func mergeEdits() map[string]*intsets.Sparse {
m := make(map[string]*intsets.Sparse)
for _, plat := range plats {
for f, e := range computeEdits(plat.goos, plat.goarch, false) {
if e0, ok := m[f]; ok {
e0.IntersectionWith(e)
} else {
m[f] = e
}
}
}
return m
}
type noImporter struct{}
func (noImporter) Import(path string) (*types.Package, error) {
panic("golang.org/x/tools/go/loader said this wouldn't be called")
}
func computeEdits(os, arch string, cgoEnabled bool) map[string]*intsets.Sparse {
ctxt := build.Default
ctxt.GOOS = os
ctxt.GOARCH = arch
ctxt.CgoEnabled = cgoEnabled
var conf loader.Config
conf.Build = &ctxt
conf.TypeChecker.Importer = noImporter{}
for _, arg := range flag.Args() {
conf.Import(arg)
}
prog, err := conf.Load()
if err != nil {
log.Fatal(err)
}
type res struct {
file string
edits *intsets.Sparse
}
ch := make(chan res)
var wg sync.WaitGroup
for _, pkg := range prog.InitialPackages() {
for _, file := range pkg.Files {
pkg, file := pkg, file
wg.Add(1)
go func() {
defer wg.Done()
v := visitor{pkg: pkg, file: conf.Fset.File(file.Package)}
ast.Walk(&v, file)
ch <- res{v.file.Name(), &v.edits}
}()
}
}
go func() {
wg.Wait()
close(ch)
}()
m := make(map[string]*intsets.Sparse)
for r := range ch {
m[r.file] = r.edits
}
return m
}
type visitor struct {
pkg *loader.PackageInfo
file *token.File
edits intsets.Sparse
}
func (v *visitor) Visit(node ast.Node) ast.Visitor {
if call, ok := node.(*ast.CallExpr); ok {
v.unconvert(call)
}
return v
}
func (v *visitor) unconvert(call *ast.CallExpr) {
// TODO(mdempsky): Handle useless multi-conversions.
// Conversions have exactly one argument.
if len(call.Args) != 1 || call.Ellipsis != token.NoPos {
return
}
ft, ok := v.pkg.Types[call.Fun]
if !ok {
fmt.Println("Missing type for function")
return
}
if !ft.IsType() {
// Function call; not a conversion.
return
}
at, ok := v.pkg.Types[call.Args[0]]
if !ok {
fmt.Println("Missing type for argument")
}
if isUntypedValue(call.Args[0], &v.pkg.Info) {
// Workaround golang.org/issue/13061.
return
}
if !types.Identical(ft.Type, at.Type) {
// A real conversion.
return
}
v.edits.Insert(v.file.Offset(call.Lparen))
}
func isUntypedValue(n ast.Expr, info *types.Info) (res bool) {
switch n := n.(type) {
case *ast.BinaryExpr:
switch n.Op {
case token.SHL, token.SHR:
// Shifts yield an untyped value if their LHS is untyped.
return isUntypedValue(n.X, info)
case token.EQL, token.NEQ, token.LSS, token.GTR, token.LEQ, token.GEQ:
// Comparisons yield an untyped boolean value.
return true
case token.ADD, token.SUB, token.MUL, token.QUO, token.REM,
token.AND, token.OR, token.XOR, token.AND_NOT,
token.LAND, token.LOR:
return isUntypedValue(n.X, info) && isUntypedValue(n.Y, info)
}
case *ast.UnaryExpr:
switch n.Op {
case token.ADD, token.SUB, token.NOT, token.XOR:
return isUntypedValue(n.X, info)
}
case *ast.BasicLit:
// Basic literals are always untyped.
return true
case *ast.ParenExpr:
return isUntypedValue(n.X, info)
case *ast.SelectorExpr:
return isUntypedValue(n.Sel, info)
case *ast.Ident:
if obj, ok := info.Uses[n]; ok {
if obj.Pkg() == nil && obj.Name() == "nil" {
// The universal untyped zero value.
return true
}
if b, ok := obj.Type().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 {
// Reference to an untyped constant.
return true
}
}
case *ast.CallExpr:
if b, ok := asBuiltin(n.Fun, info); ok {
switch b.Name() {
case "real", "imag":
return isUntypedValue(n.Args[0], info)
case "complex":
return isUntypedValue(n.Args[0], info) && isUntypedValue(n.Args[1], info)
}
}
}
return false
}
func asBuiltin(n ast.Expr, info *types.Info) (*types.Builtin, bool) {
for {
paren, ok := n.(*ast.ParenExpr)
if !ok {
break
}
n = paren.X
}
ident, ok := n.(*ast.Ident)
if !ok {
return nil, false
}
obj, ok := info.Uses[ident]
if !ok {
return nil, false
}
b, ok := obj.(*types.Builtin)
return b, ok
}