-
Notifications
You must be signed in to change notification settings - Fork 3
/
codesweep.go
92 lines (78 loc) · 1.68 KB
/
codesweep.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
package main
import (
"flag"
"fmt"
"go/ast"
"go/types"
"log"
"sort"
"github.com/kisielk/gotool"
"golang.org/x/tools/go/loader"
)
func main() {
flag.Parse()
importPaths := gotool.ImportPaths(flag.Args())
if len(importPaths) == 0 {
return
}
var conf loader.Config
for _, importPath := range importPaths {
conf.Import(importPath)
}
prog, err := conf.Load()
if err != nil {
log.Fatal(err)
}
used := make(map[string]bool)
for _, pkg := range prog.InitialPackages() {
for sym, obj := range pkg.Uses {
if !interesting(sym, obj) {
continue
}
used[obj.Id()] = true
}
}
var msgs []string
for _, pkg := range prog.InitialPackages() {
for sym, obj := range pkg.Defs {
if !interesting(sym, obj) {
continue
}
if !used[obj.Id()] {
msgs = append(msgs, fmt.Sprint(conf.Fset.Position(sym.Pos()), obj))
}
}
}
sort.Strings(msgs)
for _, msg := range msgs {
fmt.Println(msg)
}
}
func interesting(sym *ast.Ident, obj types.Object) bool {
// Skip blank identifiers.
if sym.Name == "_" {
return false
}
// Skip identifiers that don't actually declare objects (e.g., package names).
if obj == nil {
return false
}
// Skip universal objects.
if obj.Pkg() == nil {
return false
}
// Fields and methods are interesting.
if obj, ok := obj.(*types.Var); ok && obj.IsField() {
return true
}
if sig, ok := obj.Type().(*types.Signature); ok && sig.Recv() != nil {
return true
}
// Objects declared at packages scope are interesting,
// except for init and main.
if obj.Parent() == obj.Pkg().Scope() && !(sym.Name == "init" || sym.Name == "main" && obj.Pkg().Name() == "main") {
return true
}
// Otherwise, ignore for now.
return false
}