Skip to content

Commit c37866e

Browse files
committed
maligned: update to use x/tools/go/analysis
1 parent d80366f commit c37866e

File tree

1 file changed

+27
-33
lines changed

1 file changed

+27
-33
lines changed

maligned.go

+27-33
Original file line numberDiff line numberDiff line change
@@ -6,52 +6,46 @@ package main
66

77
import (
88
"flag"
9-
"fmt"
109
"go/ast"
1110
"go/build"
1211
"go/token"
1312
"go/types"
14-
"log"
1513
"sort"
1614

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"
1919
)
2020

21-
var fset = token.NewFileSet()
21+
const Doc = "TODO"
2222

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+
}
3029

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),
4034
}
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))
5038
}
51-
}
39+
})
40+
return nil, nil
41+
}
42+
43+
func main() {
44+
flag.Parse()
45+
singlechecker.Main(Analyzer)
5246
}
5347

54-
func malign(pos token.Pos, str *types.Struct) {
48+
func malign(pass *analysis.Pass, pos token.Pos, str *types.Struct) {
5549
wordSize := int64(8)
5650
maxAlign := int64(8)
5751
switch build.Default.GOARCH {
@@ -64,7 +58,7 @@ func malign(pos token.Pos, str *types.Struct) {
6458
s := gcSizes{wordSize, maxAlign}
6559
sz, opt := s.Sizeof(str), optimalSize(str, &s)
6660
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)
6862
}
6963
}
7064

0 commit comments

Comments
 (0)