|
| 1 | +package setval |
| 2 | + |
| 3 | +import ( |
| 4 | + "go/ast" |
| 5 | + "go/token" |
| 6 | + "go/types" |
| 7 | + "golang.org/x/tools/go/analysis" |
| 8 | +) |
| 9 | + |
| 10 | +var Analyzer = &analysis.Analyzer{ |
| 11 | + Name: "setval", |
| 12 | + Doc: "find Cmder types that are missing a SetVal method", |
| 13 | + |
| 14 | + Run: func(pass *analysis.Pass) (interface{}, error) { |
| 15 | + cmderTypes := make(map[string]token.Pos) |
| 16 | + typesWithSetValMethod := make(map[string]bool) |
| 17 | + |
| 18 | + for _, file := range pass.Files { |
| 19 | + for _, decl := range file.Decls { |
| 20 | + funcName, receiverType := parseFuncDecl(decl, pass.TypesInfo) |
| 21 | + |
| 22 | + switch funcName { |
| 23 | + case "Result": |
| 24 | + cmderTypes[receiverType] = decl.Pos() |
| 25 | + case "SetVal": |
| 26 | + typesWithSetValMethod[receiverType] = true |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + for cmder, pos := range cmderTypes { |
| 32 | + if !typesWithSetValMethod[cmder] { |
| 33 | + pass.Reportf(pos, "%s is missing a SetVal method", cmder) |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return nil, nil |
| 38 | + }, |
| 39 | +} |
| 40 | + |
| 41 | +func parseFuncDecl(decl ast.Decl, typesInfo *types.Info) (funcName, receiverType string) { |
| 42 | + funcDecl, ok := decl.(*ast.FuncDecl) |
| 43 | + if !ok { |
| 44 | + return "", "" // Not a function declaration. |
| 45 | + } |
| 46 | + |
| 47 | + if funcDecl.Recv == nil { |
| 48 | + return "", "" // Not a method. |
| 49 | + } |
| 50 | + |
| 51 | + if len(funcDecl.Recv.List) != 1 { |
| 52 | + return "", "" // Unexpected number of receiver arguments. (Can this happen?) |
| 53 | + } |
| 54 | + |
| 55 | + receiverTypeObj := typesInfo.TypeOf(funcDecl.Recv.List[0].Type) |
| 56 | + if receiverTypeObj == nil { |
| 57 | + return "", "" // Unable to determine the receiver type. |
| 58 | + } |
| 59 | + |
| 60 | + return funcDecl.Name.Name, receiverTypeObj.String() |
| 61 | +} |
0 commit comments