github.com/prysmaticlabs/prysm@v1.4.4/tools/analyzers/maligned/analyzer.go (about) 1 // Package maligned implements a static analyzer to ensure that Go structs take up the least possible memory. 2 package maligned 3 4 import ( 5 "errors" 6 "go/ast" 7 "go/types" 8 9 "golang.org/x/tools/go/analysis" 10 "golang.org/x/tools/go/analysis/passes/inspect" 11 "golang.org/x/tools/go/ast/inspector" 12 ) 13 14 // Doc explaining the tool. 15 const Doc = "Tool to detect Go structs that would take less memory if their fields were sorted." 16 17 // Analyzer runs static analysis. 18 var Analyzer = &analysis.Analyzer{ 19 Name: "maligned", 20 Doc: Doc, 21 Requires: []*analysis.Analyzer{inspect.Analyzer}, 22 Run: run, 23 } 24 25 func run(pass *analysis.Pass) (interface{}, error) { 26 inspection, ok := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) 27 if !ok { 28 return nil, errors.New("analyzer is not type *inspector.Inspector") 29 } 30 31 nodeFilter := []ast.Node{ 32 (*ast.StructType)(nil), 33 } 34 35 inspection.Preorder(nodeFilter, func(node ast.Node) { 36 if s, ok := node.(*ast.StructType); ok { 37 if err := malign(node.Pos(), pass.TypesInfo.Types[s].Type.(*types.Struct)); err != nil { 38 pass.Reportf(node.Pos(), err.Error()) 39 } 40 } 41 }) 42 43 return nil, nil 44 }