@@ -6,52 +6,46 @@ package main
6
6
7
7
import (
8
8
"flag"
9
- "fmt"
10
9
"go/ast"
11
10
"go/build"
12
11
"go/token"
13
12
"go/types"
14
- "log"
15
13
"sort"
16
14
17
- "github.com/kisielk/gotool"
18
- "golang.org/x/tools/go/loader"
15
+ "golang.org/x/tools/go/analysis"
16
+ "golang.org/x/tools/go/analysis/passes/inspect"
17
+ "golang.org/x/tools/go/analysis/singlechecker"
18
+ "golang.org/x/tools/go/ast/inspector"
19
19
)
20
20
21
- var fset = token . NewFileSet ()
21
+ const Doc = "TODO"
22
22
23
- func main () {
24
- flag .Parse ()
25
-
26
- importPaths := gotool .ImportPaths (flag .Args ())
27
- if len (importPaths ) == 0 {
28
- return
29
- }
23
+ var Analyzer = & analysis.Analyzer {
24
+ Name : "maligned" ,
25
+ Doc : Doc ,
26
+ Requires : []* analysis.Analyzer {inspect .Analyzer },
27
+ Run : run ,
28
+ }
30
29
31
- var conf loader.Config
32
- conf .TypeChecker .Sizes = types .SizesFor (build .Default .Compiler , build .Default .GOARCH )
33
- conf .Fset = fset
34
- for _ , importPath := range importPaths {
35
- conf .Import (importPath )
36
- }
37
- prog , err := conf .Load ()
38
- if err != nil {
39
- log .Fatal (err )
30
+ func run (pass * analysis.Pass ) (interface {}, error ) {
31
+ inspect := pass .ResultOf [inspect .Analyzer ].(* inspector.Inspector )
32
+ nodeFilter := []ast.Node {
33
+ (* ast .StructType )(nil ),
40
34
}
41
-
42
- for _ , pkg := range prog .InitialPackages () {
43
- for _ , file := range pkg .Files {
44
- ast .Inspect (file , func (node ast.Node ) bool {
45
- if s , ok := node .(* ast.StructType ); ok {
46
- malign (node .Pos (), pkg .Types [s ].Type .(* types.Struct ))
47
- }
48
- return true
49
- })
35
+ inspect .Preorder (nodeFilter , func (node ast.Node ) {
36
+ if s , ok := node .(* ast.StructType ); ok {
37
+ malign (pass , node .Pos (), pass .TypesInfo .Types [s ].Type .(* types.Struct ))
50
38
}
51
- }
39
+ })
40
+ return nil , nil
41
+ }
42
+
43
+ func main () {
44
+ flag .Parse ()
45
+ singlechecker .Main (Analyzer )
52
46
}
53
47
54
- func malign (pos token.Pos , str * types.Struct ) {
48
+ func malign (pass * analysis. Pass , pos token.Pos , str * types.Struct ) {
55
49
wordSize := int64 (8 )
56
50
maxAlign := int64 (8 )
57
51
switch build .Default .GOARCH {
@@ -64,7 +58,7 @@ func malign(pos token.Pos, str *types.Struct) {
64
58
s := gcSizes {wordSize , maxAlign }
65
59
sz , opt := s .Sizeof (str ), optimalSize (str , & s )
66
60
if sz != opt {
67
- fmt . Printf ( "%s: struct of size %d could be %d\n " , fset . Position ( pos ) , sz , opt )
61
+ pass . Reportf ( pos , " struct of size %d could be %d" , sz , opt )
68
62
}
69
63
}
70
64
0 commit comments